How to know which child an item is for its parent

511 Views Asked by At

I have a multiple choice list view and for its adapter I have designed a layout file. I have an image view in the layout and when it's clicked, I want to know what child of the list it is. I mean the child id for the its parent which is the list to further use the method list.getChildAt(???). can anyone tell me how to get that?

The image is independent of the list view and for its onClick attribute I've written a different method that changes image view resource... How can I know which child that a particular imageView is when I click on it?

In the XML layout I have this:

<ImageView
    android:id="@+id/choice_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="deleteSelected" />

And here is a part of deleteSelected method:

public void deleteSelected(View view) {

    icon = (ImageView)view.findViewById(R.id.choice_image);

    list.getChildAt(???); \\ To know which child the view is        

}

I have set the adapter as follows:

list.setAdapter(new ArrayAdapter<String>(this, R.layout.list_choice_multiple,
            R.id.choice_text, terms) {

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

        View v = super.getView(position, convertView, parent);

        icon = (ImageView)v.findViewById(R.id.choice_image);

        icon.setImageResource(R.drawable.delete_off);

        icon.setTag(R.drawable.delete_off);

        return v;
    }
});

How can I set the id for each image view so I can access it by getID() method within deleteSelected()?

3

There are 3 best solutions below

1
On

ListView has a getFirstVisiblePosition method, using that you can calculate the child position based on its position in the list view (which is a parameter passed in to the onItemClicked method of the listener).

int childIndex = listView.getFirstVisiblePosition() - position;

If you're clicking on a child of the row view (View used in the ListView, created by the adapter), then you need to know which position the row belongs too - simplest way is to store the position in the tag of the child when you set the onClickListener

2
On

Basically first you will have to set an onClickListener for your list-item's ImageView in getView() of the Adaptor.

Now with onClickListener you get the view that is clicked as function parameter to onClick(). Set a different background for this view (ImageView) object.

Hope this is clear. Let me know.

4
On

Simple answer: You are writing that the click happens on the ImageView. The ImageView is not associated with the ListView. So there is no relationship between your click or any element in the ListView. When clicking on the ImageView, though, the onClick receives a reference to the ListView itself. So what you are trying to achieve? Please be more precise.