Issue
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.
Solution
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.
Answered By - firegloves
Answer Checked By - Timothy Miller (JavaFixing Admin)