I'm making my first Android application and I'm having a problem for which I can't find the answer anywhere on Google.
I want a list of items with checkboxes. I want both the item itself and the checkbox to be clickable.
public class MyItem extends ListActivity {
private ArrayList<MyItem> items;
public void onCreate(Bundle savedInstanceState) {
/* code which creates instances of MyItem and inserts them on the *list* variable */
MyArrayAdapter adapter = new MyArrayAdapter(this, R.layout.my_item, list);
setListAdapater(adapter);
setContentView(R.layout.items_list);
}
public onListItemClick(ListView l, View v, int position, long id){
//handles the click on an item
}
public class MyArrayAdapter extends ArrayAdapter<MyItem>{
private MyItem item;
public MyArrayAdapter(Context context, int resourceId, ArrayList<MyItem> list){
//code for the constructor
}
public getView(int position, View convertView, ViewGroup parent){
convertView = inflater.inflate(resourceId, null);
this.item = list.get(position);
if (this.item == null) {
return convertView;
}
else{
if (resourceId == R.layout.my_item) {
final CheckBox cb = (CheckBox)convertView.findViewById(R.id.checkbox);
if(cb != null){
//initially
if(chosen)
cb.setChecked(true);
else
cb.setChecked(false);
//set listener
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(cb.isChecked())
chosen = true;
else
chosen = false;
}
});
}
}
return convertView;
}
}
}
Don't worry about the chosen variable. I wrote that to simply the code. It actually corresponds to a value in a database. The clicking on an item works just fine. However when I click on a checkbox what happens is this:
- the checkbox in which I clicked appears selected (this is the work of the Android's UI)
- the checkbox that internally is checked is the last one on the screen whichever it is, i.e., if I my screen displays 8 items and I click in one of them (doesn't matter which one) the check appears in the correct checkbox but internally, the 8th item is the one getting checked.
I would appreciate any help you could provide me. Thanks in advance.