CheckBox本为复选框,仍然可以当单选框用
自定义ListView item中包含一个textview 和checkbox,checkbox选中级别高于item,故在xml中进行屏蔽
单选方法:(该方法同样适用于radiobutton)
main.xml
GroupAdapter.java
public class GroupAdapter extends BaseAdapter {
private Activity activity;//上下文 private ArrayListlist;
private LayoutInflater inflater=null;//导入布局
private int temp=-1;
this.activity = context;
this.list = list;
inflater=LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
//listview每显示一行数据,该函数就执行一次
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
if (convertView==null) {//当第一次加载ListView控件时 convertView为空
convertView=inflater.inflate(R.layout.group_item_view, null);//所以当ListView控件没有滑动时都会执行这条语句
holder=new ViewHolder();
holder.tv=(TextView)convertView.findViewById(R.id.item_tv);
holder.cb=(CheckBox)convertView.findViewById(R.id.item_cb);
convertView.setTag(holder);//为view设置标签
}
else{//取出holder
holder=(ViewHolder) convertView.getTag();//the Object stored in this view as a tag
}
//设置list的textview显示
holder.tv.setTextColor(Color.WHITE);
holder.tv.setText(list.get(position));
// 根据isSelected来设置checkbox的选中状况
holder.cb.setId(position);//对checkbox的id进行重新设置为当前的position
holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//把上次被选中的checkbox设为false
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){//实现checkbox的单选功能,同样适用于radiobutton
if(temp!=-1){
//找到上次点击的checkbox,并把它设置为false,对重新选择时可以将以前的关掉
CheckBox tempCheckBox=(CheckBox)activity.findViewById(temp);
if(tempCheckBox!=null)
tempCheckBox.setChecked(false);
}
temp=buttonView.getId();//保存当前选中的checkbox的id值
}
}
});
//System.out.println("temp:"+temp);
//System.out.println("position:"+position);
if(position==temp)//比对position和当前的temp是否一致
holder.cb.setChecked(true);
else
holder.cb.setChecked(false);
return convertView;
}
static class ViewHolder {
TextView tv;
CheckBox cb;
}
}
listview checkbox实现多选框
MainAcitvity.java
GroupAdapter.java
public class GroupAdapter extends BaseAdapter {
private Context context;//上下文
private ArrayListlist; //控制CheckBox选中情况
private static HashMapisSelected;
private LayoutInflater inflater=null;//导入布局
public GroupAdapter(Context context, ArrayListlist) {
this.context = context; this.list = list;
inflater=LayoutInflater.from(context);
isSelected=new HashMap();
initData(); }
private void initData(){//初始化isSelected的数据
for(int i=0;igetIsSelected(){ return isSelected; }
public static void setIsSelected(HashMapisSelected){
GroupAdapter.isSelected=isSelected;
}
}