这个是使用ViewHolder常见的问题
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
info = list.get(i);
ViewHolder viewHolder;
if(view==null) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(getContext()).inflate(itemId, null);
viewHolder.imageView = view.findViewById(R.id.app_icon);
viewHolder.textView = view.findViewById(R.id.app_packagename);
viewHolder.checkBox = view.findViewById(R.id.app_chechbox);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
if(checkingArray[i]==true){
viewHolder.checkBox.setChecked(true);
Log.d("click"+i+"", " set checkbox true");
}else{
viewHolder.checkBox.setChecked(false);
}
viewHolder.imageView.setImageDrawable(info.icon);
viewHolder.textView.setText(info.packageName);
final int a =i;
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.d("check"+a, "onCheckedChanged: ");
if (b) {
App.bannedApplicationList.add(info.packageName);
// info.ifChecked = true;
checkingArray[a] = true;
Log.d("click"+a, "set true");
}else{
// info.ifChecked = false;
// Log.d("listLength",App.bannedApplicationList.size()+"");
}
}
});
int length = checkingArray.length;
for(int k=0;k<length;k++){
if(checkingArray[k]==false){
}
}
return view;
}
只放出getView部分的代码
首先需要记一下点击checkbox时候的状态,这个状态的可以在List的实体类中添加一个布尔变量记录,那么判断这view的时候,如果true的话在set一下就可以。
但是经过观察:
在点击前面四个checkboxbox时,控制台输出
Log.d("check"+a, "onCheckedChanged: ");
没有问题,但是在向下滑动时候,会错误的认为其他的item也被点击。
这样,只需要换一个监听器就行(我还把item也设置为false)
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
info = list.get(i);
ViewHolder viewHolder;
if(view==null) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(getContext()).inflate(itemId, null);
viewHolder.imageView = view.findViewById(R.id.app_icon);
viewHolder.textView = view.findViewById(R.id.app_packagename);
viewHolder.checkBox = view.findViewById(R.id.app_chechbox);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
if(checkingArray[i]==true){
viewHolder.checkBox.setChecked(true);
Log.d("click"+i+"", " set checkbox true");
}else{
viewHolder.checkBox.setChecked(false);
}
viewHolder.imageView.setImageDrawable(info.icon);
viewHolder.textView.setText(info.packageName);
final int a =i;
viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkingArray[a] = true;
Log.d("click"+a, "onClick: ");
}
});
return view;
}