Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

android - RecyclerView - get all existing views/viewholders

I want to update the RecyclerView while it's displaying data, in my case, I show images with or without labels.

Defaultly I set the visibility of the label when I create the view holder and that's fine, but I want the user to change the labels visibility through the menu while the RecyclerView is shown, so I want to manually update the visibility for all existing views in the RecyclerView.

Can I somehow get all existing Views? I need all, not only the visible ones, I don't want that a later recycled View is not updated...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First you need to get all the views' indices that are shown, and then you need to go over each, and use the viewHolder of each view:

final int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
final int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
for (int i = firstVisibleItemPosition; i <= lastVisibleItemPosition; ++i) {
    ViewHolder holder = (ViewHolder) mRecyclerView.findViewHolderForAdapterPosition(i);
    ...
    }

EDIT: seems it doesn't always return all ViewHolders you might want to handle. This seems like a more stable solution:

for (int childCount = recyclerView.getChildCount(), i = 0; i < childCount; ++i) {
   final ViewHolder holder = recyclerView.getChildViewHolder(recyclerView.getChildAt(i));
   ...
   }

Note: on some cases, you might want to set the number of Views being cached to be large enough so that you will always get the same views recycled, instead of new ones. For this, you can use something like that:

fun RecyclerView.setMaxViewPoolSize(maxViewTypeId: Int, maxPoolSize: Int) {
    for (i in 0..maxViewTypeId)
        recycledViewPool.setMaxRecycledViews(i, maxPoolSize)
}

Example usage:

recyclerView.setMaxViewPoolSize(MAX_TYPE_ITEM, Int.MAX_VALUE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...