ListView.getItemAtPosition(i) equivalent in RecyclerView?
Asked Answered
D

1

0

I'm migrating from a ListView backed by a CursorAdapter, to a RecyclerView backed by shywim's CursorRecyclerAdapter.

I'm having trouble migrating this part that used to return a cursor object:

(MyCursor)mListView.getItemAtPosition(i)

How to get access to cursor at specific position inside RecyclerView? Thanks.

Dreamy answered 17/3, 2015 at 18:36 Comment(0)
C
2

Unfortunately it is not part of the RecyclerView. To overcome it I define an interface:

  public interface OnItemClickListener {
        public void onItemClick(View view, int position);
  }

The ViewHolder implements the View.OnClickListener, and its constructor takes an object that implements my OnItemClickListener interface:

 public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    private OnItemClickListener mListener;

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);

    }

     public ViewHolder(View itemView, OnItemClickListener listener) {
        this(itemView);
        mListener = listener;
    }


    @Override
    public void onClick(View v) {
        if (mListener != null) {
            mListener.onItemClick(v, getPosition());
        }
    }

When you click on the row, I forward trough the listener the view clicked and its position

Corky answered 17/3, 2015 at 18:44 Comment(5)
If your List<model> position == your click position, you can just return the model at that position.Cephalothorax
yes of course.. still once you have the position, you can access the model through the adapterCorky
I have used similar solutions, I am just saying. Your solution is better because it handles all cases.Cephalothorax
This only shows how to get the position of the holder, but doesn't explain how to get at the cursor data at that position.Dreamy
The data is hold by the adapter. Ask to itCorky

© 2022 - 2024 — McMap. All rights reserved.