Reputation: 104
I have a ListView with around 10 list items. In each list item I have a checkbox. At single time I would like to have only single check box checked.
If I select row 1 then all rest of 9 checkboxes should be unchecked and so on.
Please suggest me a solution.
Currently I'm struggling with this when the list is scrolled
Upvotes: 0
Views: 225
Reputation: 1242
What you should do is you should track the last checked item, and in the ListView
's onItemClickListener
, setChecked(true);
the current item and setChecked(false);
the last one; something like this:
ListView myListView = (ListView)findViewById(/* id of listView */);
CheckBox lastChecked = null;
myListView.setOnItemClickListener(new onItemClickListener(
@Override
onItemClick(AdapterView arg0, View childView, int pos) {
if(lastChecked != null) {
lastCheckedBox.setChecked(false);
}
lastChecked = (CheckBox)((ViewGroup)childView).findViewById(/* id of checkBox */);
lastChecked.setChecked(true);
}
));
Upvotes: 1
Reputation: 21087
private Map<String, Boolean> checkState;
public CustomAdapter(Context context) {
this.checkState = new ArrayList<Boolean>(group_list.length);
}
@Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
final ViewHolder holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_check_box, null);
holder.checkbox = (Button)convertView.findViewById(R.id.checkbox);
if(checkState.containsKey(String.valueOf(position))) {
holder.checkbox.setBackgroundResource(R.drawable.fill_check_button);
holder.checkbox.setTag("0");
}else{
holder.checkbox.setBackgroundResource(R.drawable.unfill_check_button);
holder.checkbox.setTag("1");
}
holder.checkbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(holder.checkbox.getTag().toString().equals("0")) {
holder.checkbox.setTag("1");
holder.checkbox.setBackgroundResource(R.drawable.fill_check_button);
checkState.put(String.valueOf(position), true);
} else {
holder.checkbox.setTag("0");
holder.checkbox.setBackgroundResource(R.drawable.un_fill_check_button);
checkState.put(String.valueOf(position), false);
}
}
});
}
Upvotes: 0