LinearLayoutManager.findViewByPosition() 返回 null

Héc*_*tor 2 android android-recyclerview linearlayoutmanager

我的活动显示RecyclerView带有LinearLayoutManager. 我想获取View列表中的第一项 ( )。根据这篇文章接受的答案,我可以调用LinearLayoutManager.findViewByPosition()方法,但我得到了null。为什么?

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
Run Code Online (Sandbox Code Playgroud)

adapter 包含项目,它不是空的。

Gal*_*Rom 5

一个有用的函数是 doOnPreDraw - 你应该在 RecyclerView 上调用它并将你的代码放在那里。

 rv.doOnPreDraw {
     // now it will work... 
     val view = llm.findViewByPosition(0)
   }
Run Code Online (Sandbox Code Playgroud)