How can I get the position of an item in a list when I click on a specific view?

As the title says, I want to know the exact position of the element when I click on the view inside the element.

Suppose I have the following code in the getView () method of an ArrayAdapter:

...
holder = new ViewHolder ();
holder.iconAction = (ImageView)convertView.findViewById (R.id.download_item_iconAction);
holder.iconAction.setOnClickListener (new View.OnClickListener(){
    @Override
    public void onClick (View v){
        //Item X is clicked
    }
});
...

Inside onClick () I know that click, v, but I do not know the position of the element.

Let me do the trick. I am going to save a position in ViewHolder when getView () creates a view:

public View getView (int position, View convertView, ViewGroup parent){
    ViewHolder holder;
    if (convertView == null){
        holder = new ViewHolder ();
        holder.iconAction = (ImageView)convertView.findViewById (id);
        holder.iconAction.setOnClickListener (new View.OnClickListener(){
            @Override
            public void onClick (View v){
                int pos = (Integer)v.getTag ();
            }
        });
        holder.iconWait.setTag (position);

        ...
    }else{
        holder = (ViewHolder)convertView.getTag ();
    }

    ...
}

... . , , . , 10 5 ( : 1 , ). , , , (0) . , , , , - (0).
: 0, 1, 2, 3, 4 5. (6) 0: .

- ListView OnItemClickListener:

listView = getListView ();
listView.setOnItemClickListener (new AdapterView.OnItemClickListener(){
    @Override
    public void onItemClick (AdapterView<?> parentView, View childView, int position, long id){
        ...
    }
});

, , , , , .

.

+3
4

, , , if/else. , , .

    if (convertView == null){
        holder = new ViewHolder ();
        ...
    }else{
        holder = (ViewHolder)convertView.getTag ();
    }
 holder.iconWait.setTag (position);
+7

final.

position final, getView() :

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

OnClickListener:

holder.iconAction.setOnClickListener (new View.OnClickListener(){
    @Override
    public void onClick (View v){
        ... use position here ...
    }
});
+3

Your second answer (setting a tag on an element) will work fine if you move holder.iconWait.setTag (position)outside the if / then statement, that is, you should also set the tag on the processed lines, and not just on newly made lines that are too high.

0
source

I also needed to add other data to go to onClick, and it also worked with strings.

holder.iconWait.setTag ("String data here");
0
source

Source: https://habr.com/ru/post/1796358/


All Articles