我使用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:
但是當我向下滾動listView,A字母的圖標隨機顯示爲不同於A的字母。
我在做什麼錯?