views:

176

answers:

2

Hi,

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?

A: 

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
                }
            });
    }
}
M.A. Cape
Someone posted this solution and then deleted the solution once I posed my problem with it. My problem is that my list can be altered by the user (ex: deleting a row). This messes up all the indices of the rows below the deleted row.
Andrew
I can't think of any other easier solution than what you had provided. If I were you, I would go for that one.
M.A. Cape
+1  A: 

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

Andrew