繁体   English   中英

LinearLayoutManager.findViewByPosition() 返回 null

[英]LinearLayoutManager.findViewByPosition() is returning null

我的 Activity 显示了一个带有LinearLayoutManagerRecyclerView 我想获取列表中的第一项( 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

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

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

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

这是因为AdapterRecyclerView的填充是异步的。 您可以在适配器完成填充 RecyclerView 时启动一个事件,以确保findViewByPosition向您返回某些内容。

检测 RecyclerView 何时完成填充所有可见项有点困难,因为我们应该计算每个项的大小(宽度和高度)并定义当前设备显示中可以输入的项数。

但是,如果您只需要访问第一个填充的项目,那么您可以在适配器的onBindViewHolder方法中触发您的事件,显然插入所需的控件以避免为每个添加的项目触发事件。

试试这个。

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

使用OnGlobalLayoutListener等待RecyclerView完成加载其项目:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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