medo
medo

Reputation: 479

recyclerView android get item index

this my code

i have recyclerView and i set on item click for every image this the code will be and its work without any problem when i click on item i get position and i can work with it

ImageView image = new ImageView(context);
image.setOnClickListener(this);

    @Override
    public void onClick(View v) {
        onItemClickListener.onItemClick(null, v, getAdapterPosition(), v.getId());
    }

but i have problem here see image first

enter image description here

all those image in one group so if i clicked on first image its will give me position on the group and when i click on second image will return also position of group not the image .. same for 3 4 5 ..

can i get the index of the image i clicked on it like i clicked on first image on the group its give me index 1 or clicked on third one return index 3

Upvotes: 3

Views: 12139

Answers (2)

Prason Ghimire
Prason Ghimire

Reputation: 529

You can use:

getAdapterPosition();

from inside the subclass of ViewHolder.

Upvotes: 0

viana
viana

Reputation: 515

It isn't that much of a hassle though. In your implementation of RecyclerView.Adapter, you should have:

private final OnClickListener mOnClickListener = new MyOnClickListener();

@Override
public MyViewHolder onCreateViewHolder(final ViewGroup parent, final int position) {
    View view = LayoutInflater.from(mContext).inflate(R.layout.myview, parent, false);
    view.setOnClickListener(mOnClickListener);
    return new MyViewHolder(view);
}

The onClick method:

@Override
public void onClick(final View view) {
    int itemPosition = mRecyclerView.getChildLayoutPosition(view);
    String item = mList.get(itemPosition);
    Toast.makeText(mContext, item, Toast.LENGTH_LONG).show();
}

Upvotes: 2

Related Questions