ListView中item只能选择一项的做法,ListView与radioButton结合使用

ListView中item只能选择一项的做法,ListView与radioButton结合使用,只需要adapter设置一下即可 :

  
 
public class MainCategoryAdapter extends BaseAdapter {


Context context;
List<Scope> categoryList;
// 用于记录每个RadioButton的状态,并保证只可选一个
 HashMap<String, Boolean> states = new HashMap<String, Boolean>();


public MainCategoryAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}


public NearbyMainCategoryAdapter(Context context,
List<Scope> categoryList) {
// TODO Auto-generated constructor stub
this.context = context;
this.categoryList = categoryList;
}


@Override
public int getCount() {
// TODO Auto-generated method stub


return categoryList.size();
}


@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}


@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}


@Override
public View getView(final int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if (v == null) {
holder = new ViewHolder();
v = LayoutInflater.from(context).inflate(R.layout.lv_item_category_main,
null); 

v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}

final RadioButton radiobtn = (RadioButton) v.findViewById(R.id.rbtn);
holder.rbtn = radiobtn;
holder.rbtn.setText(""+ categoryList.get(position).Name);
holder.rbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {


// 重置,确保最多只有一项被选中
for (String key : states.keySet()) {
states.put(key, false);


}
states.put(String.valueOf(position), radiobtn.isChecked());
notifyDataSetChanged();
}
});


boolean res = false;
if (states.get(String.valueOf(position)) == null
|| states.get(String.valueOf(position)) == false) {
res = false;
states.put(String.valueOf(position), false);
} else
res = true;


holder.rbtn.setChecked(res);

return v;
}


public class ViewHolder {   
RadioButton rbtn;
 
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值