第1种方法:
首先是我们的bean:
public class Bean { private boolean isChecked; private String msg = "这是一条测试数据"; public Bean(){ } public Bean(boolean isCheched) { this.isChecked = isCheched; } public boolean isChecked() { return isChecked; } public void setChecked(boolean isChecked) { this.isChecked = isChecked; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
然后在getView的时候判断状态
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder mViewHolder; if(convertView == null){ convertView = mInfater.inflate(R.layout.list_item, null); mViewHolder = new ViewHolder(convertView); convertView.setTag(mViewHolder); }else{ mViewHolder = (ViewHolder) convertView.getTag(); } mViewHolder.mTextView.setText(mDatas.get(position).getMsg()); if(mDatas.get(position).isChecked()){ //状态选中 mViewHolder.mCheckBox.setChecked(true); }else{ mViewHolder.mCheckBox.setChecked(false); } return convertView; }
这样我们就能通过bean的状态来控制checkBox的选中与否了,但是onItemCLick的时候的操作才是关键
public class MainActivity extends ActionBarActivity { private ListView mListView; private ListAdapter mAdapter; private ListmDatas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.main_listView); mDatas = new ArrayList (); for (int i = 0; i < 20; i++) { if(i == 0){ //默认选中第一个 mDatas.add(new Bean(true)); continue; } mDatas.add(new Bean(false)); } mAdapter = new ListAdapter(this, mDatas); mListView.setAdapter(mAdapter); mListView.setOnItemClickListener(mOnItemClickListener); } private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int position, long arg3) { for (Bean bean : mDatas) { //全部设为未选中 bean.setChecked(false); } mDatas.get(position).setChecked(true);//点击的设为选中 mAdapter.notifyDataSetChanged(); } };}
XML