2016-07-07 58 views
1

我使用BaseAdapter和ViewHolder模式顯示ListView。getView在列表適配器中提供的錯誤視圖

public class ListViewActivity extends AppCompatActivity { 
    private String[] letters = {"A", "B", "C", "D", 
      "E", "F", "G", "H", "I", "J", "K", "L", 
      "M", "N", "O","P", "Q"}; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.act_lv); 

     final ListView listView = (ListView) findViewById(R.id.listView); 

     listView.setAdapter(new TestBaseAdapter(this, letters)); 
    } 

    class TestBaseAdapter extends BaseAdapter { 
     private Context context; 
     private String[] values; 
     private LayoutInflater inflater; 
     public TestBaseAdapter(Context context, String[] values) { 
      this.context = context; 
      this.values = values; 
      this.inflater = LayoutInflater.from(this.context); 
     } 

     @Override 
     public int getCount() { 
      return values.length; 
     } 

     @Override 
     public Object getItem(int position) { 
      return values[position]; 

     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      MyViewHolder myViewHolder; 

      if (convertView == null) { 
       convertView = inflater.inflate(R.layout.lv_layout, parent, false); 
       myViewHolder = new MyViewHolder(convertView); 
       convertView.setTag(myViewHolder); 
      } else { 
       myViewHolder = (MyViewHolder) convertView.getTag(); 
      } 

      myViewHolder.title.setText((String)getItem(position)); 
      if (((String)getItem(position)).equals("A")) { 
       myViewHolder.icon.setImageResource(R.drawable.custom_icon); 
      } 

      return convertView; 
     } 

     private class MyViewHolder { 
      TextView title; 
      ImageView icon; 

      public MyViewHolder(View item) { 
       title = (TextView) item.findViewById(R.id.label); 
       icon = (ImageView) item.findViewById(R.id.logo); 
      } 
     } 
    } 

} 

的代碼只是顯示在列表視圖,其中每一行包含從數組中的項的數組的內容,但是,如果該項目的值是「A」,該行節目顯示不同的圖標。這種狀況在getView(...)方法的這一部分提出:

... 
if (((String)getItem(position)).equals("A")) { 
    myViewHolder.icon.setImageResource(R.drawable.custom_icon); 
} 
... 

在創建活動中,似乎一切都OK:

enter image description here

但是當我向下滾動listView,A字母的圖標隨機顯示爲不同於A的字母。

enter image description here

我在做什麼錯?

回答

4

Android正在回收列表中的視圖,並且您設置圖標「A」的視圖作爲參數傳遞給方法getView,當它不可見時。 解決的辦法是重新設置默認的圖標,就像這樣:

if (((String)getItem(position)).equals("A")) { 
    myViewHolder.icon.setImageResource(R.drawable.custom_icon); 
} else { 
    myViewHolder.icon.setImageResource(/*your default image*/); 
} 
2

必須爲所有視圖更新的圖標(而不是隻爲那些以字母「A」)。

if (((String)getItem(position)).equals("A")) { 
    myViewHolder.icon.setImageResource(R.drawable.custom_icon); 
} else { 
    myViewHolder.icon.setImageResource(R.drawable.DEFAULT_ICON_ID); 
}