progNewbie progNewbie - 1 month ago 15
Android Question

Get ID of checkbox inside of listview item in OnItemClick listener

I got a listview with items. Each item has a chekbox. Now if a item is clicked, I want to change the state of this checkbox. How can I get the ID of the checkbox when the listview item is clicked?

I got this code:

cList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
Client currentClient = (Client) mAdapter.getItem(position);

}
});

Answer

Here, we are looping through all the views inside the view object and finding CheckBox:

cList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
        Client currentClient = (Client) mAdapter.getItem(position);

        try {
            ViewGroup group = (ViewGroup) view;
            if(group != null) {
                View currView;
                for(int i = 0; i < group.getChildCount(); i++) {
                    currView = group.getChildAt(i);
                    if(currView instanceof CheckBox) {
                        CheckBox checkBox = (CheckBox) currView;    // this is your checkbox
                        int checkboxId = checkBox.getId();
                        // do something
                        break;
                    } else {
                        // these are all the other views (not checkbox)
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }
});