我知道这个问题一再被问到,但我还没有找到一个真正帮助我的建议.每当列表向下滚动时,该复选框都将被取消选中.是的,我正在使用一个布尔数组来存储值,但这仍然无法解决问题.这是我的代码请为此建议一个解决方案.谢谢.
public View getView(final int position,View convertView,ViewGroup parent) { // TODO Auto-generated method stub final ViewHolder holder; final boolean[] itemChecked=new boolean[30]; LayoutInflater inflater = context.getLayoutInflater(); if(convertView==null) { convertView = inflater.inflate(R.layout.custom_list,null); holder = new ViewHolder(); holder.txtViewTitle = (TextView) convertView.findViewById(R.id.title_text); holder.txtViewDescription = (TextView) convertView.findViewById(R.id.description_text); holder.cb=(CheckBox) convertView.findViewById(R.id.cb); convertView.setTag(holder); } else { holder=(ViewHolder)convertView.getTag(); } holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { // TODO Auto-generated method stub itemChecked[position] = isChecked; if(itemChecked[position]) { holder.cb.setChecked(true); } else { holder.cb.setChecked(false); } holder.txtViewTitle.setText(title[position]); holder.txtViewDescription.setText(description[position]); holder.cb.setChecked(itemChecked[position]); holder.txtViewDescription.setFocusable(false); holder.txtViewTitle.setFocusable(false); return convertView; } }
解决方法
每当需要绘制以前不可见的列表项时调用getView().由于每次调用此方法时都会重新创建itemChecked [],因此您将不会选中新复选框,并为每个生成的视图选择不同的数组. (Java中的final不会像C那样使该领域独一无二)
最简单的解决方法是让itemChecked成为一个类成员,并根据该选项设置/恢复复选框状态.
最简单的解决方法是让itemChecked成为一个类成员,并根据该选项设置/恢复复选框状态.
public class MyListAdapter extends ArrayAdapter<Object> { private final boolean[] mCheckedState; private final Context mContext; public MyListAdapter(Context context,int resource,int textViewResourceId,List<Object> objects) { super(context,resource,textViewResourceId,objects); mCheckedState = new boolean[objects.size()]; mContext = context; } @Override public View getView(int position,ViewGroup parent) { // simplified to just a CheckBox // ViewHolder and OnCheckedChangeListener stuff left out CheckBox result = (CheckBox)convertView; if (result == null) { result = new CheckBox(mContext); } result.setChecked(mCheckedState[position]); return result; } }