在listview的item中存在CheckBox时也会由于复用convert view导致CheckBox的选中状态错乱,本片内容将解决由于复用导致CheckBox选中状态错乱的问题。
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private List mStringList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStringList=new ArrayList<>();
mStringList.add("北京市");mStringList.add("天津市");mStringList.add("上海市");mStringList.add("重庆市");
mStringList.add("河北省");mStringList.add("山西省");mStringList.add("辽宁省");mStringList.add("河南省");
mStringList.add("山东省");mStringList.add("湖北省");mStringList.add("湖南省");mStringList.add("江西省");
mStringList.add("福建省");mStringList.add("陕西省");mStringList.add("四川省");mStringList.add("台湾省");
mListView= (ListView) findViewById(R.id.lv_main);
MyAdapter adapter=new MyAdapter(this,mStringList);
mListView.setAdapter(adapter);
}
}
public class MyAdapter extends BaseAdapter {
List mStringList;
Context mContext;
private Map map=new HashMap<>();// 存放已被选中的CheckBox
public MyAdapter(Context context, List stringList) {
mStringList = stringList;
mContext=context;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
MyViewHolder holder;
if(convertView==null){
convertView=View.inflate(mContext,R.layout.item,null);
holder=new MyViewHolder();
holder.mTextView= (TextView) convertView.findViewById(R.id.tv_item);
holder.mCheckBox= (CheckBox) convertView.findViewById(R.id.cb_item);
convertView.setTag(holder);
}else {
holder= (MyViewHolder) convertView.getTag();
}
holder.mTextView.setText(mStringList.get(position));
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked==true){
map.put(position,true);
}else {
map.remove(position);
}
}
});
if(map!=null&&map.containsKey(position)){
holder.mCheckBox.setChecked(true);
}else {
holder.mCheckBox.setChecked(false);
}
return convertView;
}
@Override
public int getCount() {
return mStringList.size();
}
@Override
public Object getItem(int position) {
return null;
}
public static class MyViewHolder {
TextView mTextView;
CheckBox mCheckBox;
}
}
mListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
listview与checkbox会有焦点的冲突,如果需要取消的子控件焦点太多,就可以直接给布局设置
descendantFocusability="blocksDescendants" 这个属性,
布局里面的所有子控件焦点都会取消,
单个取消的话设置
focusable="false" 就OK了