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;
}
}