getChildAt(pos) 在 RecyclerView 上返回 null

Aru*_*ury 2 android android-recyclerview

我正在使用 RecyclerView,其中我有行数,每行都有更新的进度条。前四行是可见的。当行数大于 4 并且我在我的 recyclerview 上调用 getChildAt(pos) 以获取视图时,它正在返回空值。请帮忙。

Aru*_*ury 7

由于 recyclerView.getChildAt(position) 在上述情况下给我 null,我终于使用下面的行解决了。它对遇到类似情况的人很有用。

RecyclerView.ViewHolder holder = (RecyclerView.ViewHolder)
recyclerView.findViewHolderForAdapterPosition(position);
if (null != holder) {
   holder.itemView.findViewById(R.id.xyz).setVisibility(View.VISIBLE);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

当您的回收站视图中有不止一页的数据并且您正在使用getChildAt()方法时,它会抛出空指针异常。这是因为当位置大于显示器上可见项目的数量时,getChildAt()将不起作用,因为它只能到达屏幕上显示的视图。

因此,使用recyclerView.layoutManager?.findViewByPosition(position)来获取给定位置的视图。