简体   繁体   中英

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.

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)
   }

It's because the population of the RecyclerView by the Adapter is asynchronous. You may launch an event when the adapter finish to populate the RecyclerView to be sure that findViewByPosition returns something to you.

Detect when RecyclerView have finished to populate all visible items is a bit difficult, because we should calculate each item size (width and height) and define how many items can enter in current device display.

But if what you need is only to access first populated item then you can fire your event in your Adapter's onBindViewHolder method, obviously inserting the needed controls to avoid to fire events for every added item.

try this.

new Handler().postDelayed(new Runnable() {
     @Override
     public void run() {
         View firstViewItem = llm.findViewByPosition(0);
     }
 }, 500);

Use OnGlobalLayoutListener to wait for RecyclerView to finish loading its items:

myRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        // do you stuff here...
                    }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM