我正在努力使用ListViewAdapter并使用OnClickListener。 任务很简单:
适配器代码:
public class ListViewAdapter extends ArrayAdapter<StuffPics> {
Context context;
public ArrayList<Integer> mItemsChecked;
public ListViewAdapter(Context context, int resource, ArrayList<StuffPics> mylist) {
super(context, resource, mylist);
this.context = context;
mItemsChecked = new ArrayList<Integer>();
}
@Override
public View getView(final int position, View cell, ViewGroup parent) {
final Holder holder;
View v= cell;
if (v == null){
holder = new Holder();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.seepic_test, null);
holder.mainButton1 = (Button)v.findViewById(R.id.main_button1);
holder.mainButton2 = (Button)v.findViewById(R.id.main_button2);
if(mItemsChecked.size()==0 || (!mItemsChecked.contains(position) && position > mItemsChecked.get(mItemsChecked.size() - 1))){
mItemsChecked.add(position);
}
v.setTag(holder);
}else{
if(mItemsChecked.size()==0 || (!mItemsChecked.contains(position) && position > mItemsChecked.get(mItemsChecked.size() - 1))){
mItemsChecked.add(position);
}
holder = (Holder)v.getTag();
if(!mItemsChecked.contains(position)){
System.out.println("POSITION GREEN : " + Integer.toString(position));
holder.mainButton1.setVisibility(View.INVISIBLE);
holder.mainButton2.setVisibility(View.VISIBLE);
}
}
holder.mainButton1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mItemsChecked.remove(position);
holder.mainButton1.setVisibility(View.INVISIBLE);
holder.mainButton2.setVisibility(View.VISIBLE);
}
});
return v;
}
我的想法是收集mItemsChecked数组中的所有位置,然后点击按钮从该数组中删除某个位置,然后重新使用视图根据mItemsChecked数组当前状态分配它 - 如果位置仍在那里,那么蓝色按钮,如果位置不在数组中(单击按钮并移除位置),则为绿色按钮。
现在,根据日志它的工作原理。但不是根据实际观点而来)
日志:
真实观点:
我坚持到这里,因为日志与真实视图不匹配。 我究竟做错了什么 ?如何在ListView中单击的按钮上打开不同的颜色并在列表滚动期间保持它?
答案 0 :(得分:2)
您的绿色视图正在被回收。在if块
之后放一个else条件if(!mItemsChecked.contains(position)){
System.out.println("POSITION GREEN : " + Integer.toString(position));
holder.mainButton1.setVisibility(View.INVISIBLE);
holder.mainButton2.setVisibility(View.VISIBLE);
}
else{
System.out.println("POSITION Blue : " + Integer.toString(position));
holder.mainButton1.setVisibility(View.VISIBLE);
holder.mainButton2.setVisibility(View.INVISIBLE);
}