Search code examples
androidcursorandroid-recyclerview

Android : How to use recyclerView.findViewHolderForAdapterPosition inside Recycle View Cursor Adapter class


I am trying to get viewholder of a particular position from recycle view.

I had found to do so by doing this in MainActivity :

viewHolderRec = recyclerViewInstance.findViewHolderForAdapterPosition(vHID);

It works well inside my MainActivity.

But, when I tried to implement the same inside my recycle view cursor adapter like this :

I had changed the cursor to take recycleview :

In my MainActivity :

    final RecyclerView recyclerView = findViewById(R.id.recycle_view);
    LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(manager);
    recyclerView.setNestedScrollingEnabled(true);
    mCursorAdapter = new RecycleCursorAdapter(this, null, recyclerView);
    recyclerView.setAdapter(mCursorAdapter);

In RecycleCursorAdapter :

RecyclerView recyclerViewInstance;

public RecycleCursorAdapter(Context context, Cursor cursor, RecyclerView recyclerView) {
    super(context, cursor);
    recyclerViewInstance = recyclerView;
}
 @Override
public void onBindViewHolder(ChatCursorAdapter3.ViewHolder viewHolder, Cursor cursor) {
    ChatListItem myListItem = ChatListItem.fromCursor(cursor);
    int vHID = viewHolder.getAdapterPosition();

    viewHolderRec = (ViewHolder) recyclerViewInstance.findViewHolderForAdapterPosition(vHID - 1);
}

But viewHolderRec is null.

I want to get the viewholder of the view which is above the current viewHolder.

I just want to know how can I get it work. What I want is to use findViewHolderForAdapterPosition() method inside my recycle view cursor adapter.

Yes, I know that I can use

viewHolder.getOldPosition()

But It does not fulfill my needs at the time of scrolling the recycle view.

Thanks In Advance :-)


Solution

  • I had searched a lot and find that, Instead of using recyclerViewInstance.findViewHolderForAdapterPosition(vHID - 1);

    I can find the viewholder of any position by storing the viewholders in a List<> like

    List<ViewHolder> vList = new ArrayList<>();
    

    and whenever i want the viewholder of any posstion than i can find by

    int vHID = viewHolder.getAdapterPosition();
    viewHolderRec = vList.get(vHID - 1);
    

    As what i need to do.

    But, I know this effects lots of memory when the list is very large. So what I did is removing the viewholders from memory which are not visible right now.

    For this, I get the height in display pixels(dp) and get the number of visible items by it. and remove all the other viewholders.

    This trick works for me. May Be this will be helpful for someone so I posting this answer.