2015-05-12 124 views
1

我已经实现了此示例(2.自定义适配器示例) http://www.mkyong.com/android/android-gridview-example/ 它的工作原理。Android - GridView强制更新数据更改

我当时就想“刷新”用一组新的数据,直到我这样做,没有工作:

imageAdapter.notifyDataSetChanged(); 

,然后取出在ImageAdapter getView方法如下检查:

if (convertView == null) { 

这是我目前的getView方法

public View getView(int position, View convertView, ViewGroup parent) { 

    LayoutInflater inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    View gridView; 

    // if (convertView == null) { // stopped my GridView from updating !! 
    if (true) 
    { 
     gridView = new View(context); 

     // get layout from mobile.xml 
     gridView = inflater.inflate(R.layout.mobile, null); 

     // set value into textview 
     TextView textView = (TextView) gridView 
       .findViewById(R.id.grid_item_label); 

     textView.setText(mobileValues[position]); 


     // set image based on selected text 
     ImageView imageView = (ImageView) gridView 
       .findViewById(R.id.grid_item_image); 

     imageView.setImageResource(R.drawable.square); 


    } else { 
     gridView = (View) convertView; 
    } 

    return gridView; 
} 

我担心它现在正在做不必要的亲一遍又一遍地重复 - 多次膨胀视图?

我应该在每次调用这个函数时创建一个新的GridView吗?

+0

只是通知arraylist您在adapter构造函数中传递的不是整个arrayadapter。 –

回答

1

它没有工作,因为以下行

TextView textView = (TextView) gridView 
      .findViewById(R.id.grid_item_label); 

    textView.setText(mobileValues[position]); 


    // set image based on selected text 
    ImageView imageView = (ImageView) gridView 
      .findViewById(R.id.grid_item_image); 

    imageView.setImageResource(R.drawable.square); 

去外面的if/else。支票if (convertView == null)是必要的。如果你没有它,你将膨胀n不同的意见,与n == getCount()。对于n大,这将是一个问题。你可能想要实现android ViewHolder模式,为用户提供最好的UX。

正如@Vzsg所指出的那样,也摆脱了gridView = new View(context);。这是一个额外的无用的分配

+0

可能值得注意的是,下面这行:'gridView = new View(context);'是不必要的。 – vzsg

+0

@vzsg,谢谢,我编辑它 – Blackbelt

+0

好的谢谢 - 重新测试和工作正常(仍然) - 也将调查ViewHolder模式 - 不幸的是我不能标记你的答案,因为我的声誉太低!主要包括driveby降价! – NottmTony

0

我通常只是用新的结果更新适配器,并将其设置为GridView。

所以在你的例子中,当我想更新我的GridView - 我做了以下。

gridView.setAdapter(newAdapter); 

你可以有一个实用的方法,例如这将使获得一个新的适配器更容易。

private ArrayAdapter getAdapter(String [] data){...}