Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinearLayoutManager.findViewByPosition() is returning null

My Activity is showing a RecyclerView with a LinearLayoutManager. I want to get the first item (View) in the list. According this post's accepted answer , I can do it calling LinearLayoutManager.findViewByPosition() method, but I'm getting null instead. Why?

RecyclerView list = findViewById(R.id.list);
LinearLayoutManager llm = new LinearLayoutManager(this);
list.setLayoutManager(llm);
MyAdapter adapter = new MyAdapter();
list.setAdapter(adapter);
View firstViewItem = llm.findViewByPosition(0); // <-- null

adapter contains items, it's not empty.

like image 855
Héctor Avatar asked Dec 11 '25 14:12

Héctor


2 Answers

A useful function is doOnPreDraw - you should call it on the RecyclerView and put your code there.

 rv.doOnPreDraw {
     // now it will work... 
     val view = llm.findViewByPosition(0)
   }
like image 82
Gal Rom Avatar answered Dec 14 '25 07:12

Gal Rom


try this.

new Handler().postDelayed(new Runnable() {
     @Override
     public void run() {
         View firstViewItem = llm.findViewByPosition(0);
     }
 }, 500);
like image 26
Mehul Kabaria Avatar answered Dec 14 '25 07:12

Mehul Kabaria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!