I have a ListView of items that need to be checkable/uncheckable. I have set up an ArrayAdapter that is currently using android.R.layout.simple_list_item_multiple_choice as the row, and everything displays just fine. I am also able to properly get the clicks on this item. However, the Checkbox in the UI does not toggle when the item is selected. I've been trying to figure this out for a while, can anyone point me in the right direction? I just want to know how to force the UI to update to reflect the changed state of the checkbox.
I can provide code if needed, but I'm trying to look for something very specific here, so I figure posting a bunch of my code wouldn't be of much help.
Thanks!
Programmatically in java code
CheckBox mCheckBox = (CheckBox) findViewById(R.id.checkBox);
mCheckBox.setChecked(true); //to check
mCheckBox.setChecked(false); //to uncheck
In android XML
android:checked="true" //to check
android:checked="false" //to uncheck
as
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Checkbox Item" />
First of all go through my this answer: Android listview with check boxes?
Nice as you want to implement checked/unchecked check boxes in ListView, you just need to implement below lines in getView() method:
// also check this lines in the above example
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());
Also check the getView() method for the implementation of event on CheckBox residing inside the ListView:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.rowbuttonlayout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox
.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.checkbox.setChecked(list.get(position).isSelected());
// ......
}
Have you tried the following?
@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
//Invert the checkbox-status
((CheckedTextView) view.findViewById(R.id.text1)).setChecked(!isChecked());
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With