I have a list and a checkbox in every row of it. I want that whenever I click on a row, the checkbox changes its state accordingly.
checkbox.xml
<
CheckBox checkBox = (CheckBox) v.findViewById(R.id.CheckBox);
checkBox.setChecked(true);
Here is the full code, you can add this after setting the addapter:
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String message = "Item " + position;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
cb.setChecked(!cb.isChecked());
}
});
Inside the onListItemClick do this:
CheckBox cb = (CheckBox) v.findViewById(R.id.CheckBox);
cb.setChecked(!cb.isChecked());
You need to use findViewById to get a pointer to your checkbox:
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getApplicationContext(), "You have selected item no."
+(position+1)+"", Toast.LENGTH_SHORT).show();
super.onListItemClick(l, v, position, id);
if (v != null) {
CheckBox checkBox = (CheckBox)v.findViewById(R.id.Checkbox);
checkBox.setChecked(!checkBox.isChecked());
}
}
If you are recieving the onClick event then v should never be null but I have put on the appropriate checks.