如何遍历RecyclerView中的所有视图/项目? [英] How do iterate through all the views/items in a RecyclerView?
问题描述
我需要遍历RecyclerView
中的所有RadioGroups
.
我尝试的代码:
for(int i=0;i<recyclerView.getAdapter().getItemCount();i++)
{
radioGroup = recyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.radio_group);
}
但是findViewHolderForAdapterPosition(i)
对于不在屏幕上的RadioGroup返回null
并给我一个NullPointerException
.
but findViewHolderForAdapterPosition(i)
returns null
for RadioGroups that are off screen and gives me a NullPointerException
.
我如何遍历所有这些人?
How do i iterate through all of them?
推荐答案
RecyclerView视图在滚动时根据需要创建/销毁.您不能依靠它们的可用性.
RecyclerView views are created/destroyed as needed when you scroll. You cannot rely on them being available.
我假设您正在尝试检索选择状态.最好将其存储在适配器中的对象中,并在单击单选按钮时更新其值.
I assume you are trying to retrieve the selection state. It is better to store this within your object in the adapter and update its value upon clicking a radio button.
然后,您可以在适配器中实现getItem方法,该方法返回对象及其当前选择状态.
Then you can implement a getItem method in your adapter that returns the object and it's current selection state.
这篇关于如何遍历RecyclerView中的所有视图/项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!