How do iterate through all the views/items in a RecyclerView?

眉间皱痕 提交于 2020-06-26 20:32:17

问题


I need to iterate through all the RadioGroups in my RecyclerView.

Code i tried:

for(int i=0;i<recyclerView.getAdapter().getItemCount();i++)
  {
     radioGroup = recyclerView.findViewHolderForAdapterPosition(i).itemView.findViewById(R.id.radio_group);
  }

but findViewHolderForAdapterPosition(i) returns null for RadioGroups that are off screen and gives me a NullPointerException.

How do i iterate through all of them?


回答1:


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.

Then you can implement a getItem method in your adapter that returns the object and it's current selection state.



来源:https://stackoverflow.com/questions/50947445/how-do-iterate-through-all-the-views-items-in-a-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!