我有一个自定义列表视图,每行包含一个复选框和文本.现在我想要的是,如果任何一个listview行的复选框被选中,那么其他行中的其他复选框如果被选中.it将被自动选择.(即一次只能选择一个复选框).我应该怎么做.
到目前为止,我所做的工作如下:
public class CustomAdapter extends BaseAdapter{ Context context; List<String> items; boolean array[]; public CustomAdapter(Context context,List<String> items) { super(); this.context = context; this.items = items; array =new boolean[items.size()]; } @Override public int getCount() { // TODO Auto-generated method stub return items.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return items.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position,View convertView,ViewGroup parent) { // TODO Auto-generated method stub View v=convertView; final int pos=position; if(v==null) { v=LayoutInflater.from(context).inflate(R.layout.list,null); } TextView txt1=(TextView) v.findViewById(R.id.textView1); final CheckBox chkBox=(CheckBox) v.findViewById(R.id.checkBox1); txt1.setText(items.get(position)); int selectedindexitem=0; chkBox.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(chkBox.isChecked()) { array[pos]=true; }else{ array[pos]=false; } } }); chkBox.setChecked(array[pos]); return v; } } In this code i can select multiple checkBox at a time but i need only one checkBox should be checked one at a time.
解决方法
尝试更改所有项目布尔值false在通知适配器后排除选定项目,并为ListView性能实现
ViewHolder设计模式:
@Override public View getView(final int position,ViewGroup parent) { ViewHolder holder; if(convertView==null){ holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.list,null); holder.txt1 = (TextView) convertView.findViewById(R.id.textView1); holder.chkBox = (CheckBox) convertView.findViewById(R.id.checkBox1); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } holder.txt1.setText(items.get(position)); holder.chkBox.setChecked(array[position]); holder.chkBox.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { for (int i=0;i<array.length;i++){ if(i==position){ array[i]=true; }else{ array[i]=false; } } notifyDataSetChanged(); } }); return convertView; } class ViewHolder{ TextView txt1; CheckBox chkBox; }