How can I get the position of the item within a listview when I click on a specific view?

无人久伴 提交于 2019-12-05 22:17:44

You're very nearly there, all you need to do is set the tag after your if/else clause. This is to make sure the tag is updated when the view is recycled as well as when it is created from new.

e.g

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

Local anonymous classes can reference final local variables.

Make position final by changing your getView() method to read:

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

and then you can reference position from within the OnClickListener:

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

Your second answer (setting a tag on an element) would work fine if you moved holder.iconWait.setTag (position) outside of the if/then statement -- that is, you should set the tag on recycled rows too, not just on newly-inflated ones.

I also needed to add other data to pass to onClick and it worked with strings too.

holder.iconWait.setTag ("String data here");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!