2015-05-12 123 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){...}