Question

I have a ListActivity where the list items are defined in another XML layout. The list item layout contains an ImageView, a CheckBox, a TextView and such.

What I want is to set an onClick listener to the CheckBox in each list item. That is easy enough. The trouble is I need that onClick handler to know which position in the list it is.

I'm attaching the listener to the CheckBox in getView after that convertView has been inflated. The getView method has a position parameter, but I cannot reference it in the onClick handler for my CheckBox. I understand why, but I don't know how to get around it.

How do I accomplish this?

Was it helpful?

Solution

I created this method to get the position:

    private int getListPosition(View v) {
        View vParent = (View)v.getParent();
        if (vParent != null) {
            ViewGroup vg = (ViewGroup)vParent.getParent();
            if (vg != null) {
                return getListView().getFirstVisiblePosition() + vg.indexOfChild(vParent);
            }
        }
        return -1;
    }

You would pass in buttonView as the v parameter

OTHER TIPS

You can try setting a tag on the checkbox by its position and when the onCheckedChangeListener gets fired, get the tag of the checkbox to get its position..

here is a sample code but I haven't tried it

@Override
public View getView(int position, View convertView, ViewGroup parent) {

// grab view
View v = convertView;
// set view layout
if (v == null) {
    LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = vi.inflate(R.layout.layout_inbox_item, null);

    CheckBox box = (CheckBox)v.findViewById(R.id.inbox_itemcheck);
    if (box != null) {
        box.setTag(position); //<-- sets the tag by its position
        box.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    int position = (Integer)buttonView.getTag(); //<-- get the position
                }
            });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top