我有一个ListView
which extends BaseAdapter
。我有一个 data[] 数组。ListView
膨胀并正确填充。我想要做的是ImageView
在用户选择项目时在列表项目(基本上是膨胀视图右侧的检查图像)上显示一个,如果选择了前一个项目,我只是隐藏它ImageView
。这也很好。
但是在我选择一个新项目并来回滚动后,我看到了奇怪的行为,检查图像有时在多个列表项中可见,或者隐藏在当前选择的实际项目中。有人可以帮忙解释我做错了什么吗?
我在方法中有这两行onCreate
:
adap = new EfficientAdapter(this);
lstview.setAdapter(adap);
和适配器代码:
public static class EfficientAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private Context context;
private ImageView CurrentSelectedImageView;
private Integer CurrentPosition = 14;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
//Log.e("TAG",String.valueOf(position));
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adaptor_content, null);
holder = new ViewHolder();
holder.textLine = (TextView) convertView.findViewById(R.id.txtCategoryCaption);
holder.iconLine = (ImageView) convertView.findViewById(R.id.iconLine);
holder.imgCheckbox = (ImageView) convertView.findViewById(R.id.imgCheck);
//If the CurrentPosition == position then make the checkbox visible else dont.
if (CurrentPosition == position){
holder.imgCheckbox.setVisibility(View.VISIBLE);
}else{
holder.imgCheckbox.setVisibility(View.INVISIBLE);
}
final ImageView Checkbox = holder.imgCheckbox;
//Now if the list item is clicked then set the position as the current item and make the checkbox visible.
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
@Override
public void onClick(View v) {
if (CurrentSelectedImageView!=null){
CurrentSelectedImageView.setVisibility(View.INVISIBLE);
}
Checkbox.setVisibility(View.VISIBLE);
CurrentSelectedImageView = Checkbox;
CurrentPosition = pos;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
int id = context.getResources().getIdentifier("nodeinsert", "drawable", context.getString(R.string.package_str));
if (id != 0x0) {
mIcon1 = BitmapFactory.decodeResource(context.getResources(), id);
}
holder.iconLine.setImageBitmap(mIcon1);
holder.textLine.setText(String.valueOf(data[position]));
if (CurrentPosition == position){
Log.e("TAG",CurrentPosition + "---" + String.valueOf(position));
holder.imgCheckbox.setVisibility(View.VISIBLE);
}else{
holder.imgCheckbox.setVisibility(View.INVISIBLE);
}
return convertView;
}
static class ViewHolder {
TextView textLine;
ImageView iconLine;
ImageView imgCheckbox;
}
@Override
public Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
}