android - LinearLayoutManager.findViewByPosition() 返回 null

标签 android android-recyclerview linearlayoutmanager

我的 Activity 正在显示一个带有 LinearLayoutManagerRecyclerView。我想获取列表中的第一项 (View)。根据this post's accepted answer ,我可以调用 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

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

最佳答案

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

 rv.doOnPreDraw {
     // now it will work... 
     val view = llm.findViewByPosition(0)
   }

关于android - LinearLayoutManager.findViewByPosition() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46326681/

相关文章:

android - 升级到 ADT 20 后,键盘在 Intel x86 Android 模拟器上停止工作

java - 当我点击 "+"按钮时,我应该显示 2,再次点击它应该显示 3。

android - 为 RecyclerView 中的其他项目重复图片

android - 一个LinearLayoutManager只能对应一个RecyclerView?

android - 如何在更改布局管理器时为 Recycler-View 设置动画

android - 当我尝试在选项卡之间切换时应用程序崩溃

java - 软键盘隐藏EditText

android - ?安卓 :attr/selectableItemBackground not working on white windowBackground

android - RecyclerView 中的预取文本布局,无法解析方法 setTextFuture

android - 如何以编程方式更改 RecyclerView 中项目的位置?