0

I want to get Viewholder of first completely visible item of my RecyclerView with this code :

myRecyclerView = (RecyclerView) findViewById(R.id.recycler_demo);
myRecyclerView.setHasFixedSize(true);
myLayoutManager = new LinearLayoutManager(getApplicationContext())
myRecyclerView.setLayoutManager(myLayoutManager);
LinearCardListAdapter myAdapter = new LinearCardListAdapter(getApplicationContext(), initilizeData());
myRecyclerView.setAdapter(myAdapter);
ImageView iv = new ImageView(this);
int adapterPosition = myLayoutManager.findFirstCompletelyVisibleItemPosition();
RecyclerView.ViewHolder visibleViewHolder = myRecyclerView.findViewHolderForAdapterPosition(adapterPosition);

In this case visibleViewHolder is null.

also I tried findViewHolderForAdapterPosition with numbers from 0 to 7 (my dataset is from 0 to 7 with 8 data ) and again I got null;

any solution ?

Tom Sabel
  • 3,935
  • 33
  • 45
Mohammad Fatemi
  • 1,278
  • 2
  • 12
  • 16
  • Since you call `notifyDataSetChanged()` before it, you get `null`, because the layout is not ready yet. "Note that when Adapter contents change, ViewHolder positions are not updated until the next layout calculation. If there are pending adapter updates, the return value of this method may not match your adapter contents. You can use #getAdapterPosition() to get the current adapter position of a ViewHolder."[doc](https://developer.android.com/intl/zh-cn/reference/android/support/v7/widget/RecyclerView.html#findViewHolderForAdapterPosition(int)) – yennsarah Mar 30 '16 at 13:32
  • 1
    Possible duplicate of [Android recyclerView findViewHolderForAdapterPosition returns null](http://stackoverflow.com/questions/32836844/android-recyclerview-findviewholderforadapterposition-returns-null) – yennsarah Mar 30 '16 at 13:37
  • @Amy Hi `notifyDataSetChanged()` wasn't at my code I forgot to remove it in the question but it's not at my code. So it's not the problem – Mohammad Fatemi Mar 30 '16 at 13:54

1 Answers1

0

you can do this:

   myRecyclerView.postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    if(myRecyclerView.findViewHolderForAdapterPosition(0)!=null )
                    {

                        RecyclerView.ViewHolder visibleViewHolder=myRecyclerView.findViewHolderForAdapterPosition(0);
                    }
                }
            },50);
Dharmaraj
  • 1,256
  • 13
  • 12