ViewHolder is not like an inner class

Is it possible to use RecyclerView.ViewHolder not as an inner class? Are there any problems with this?

I searched, but havent found any documentation on it!

+4
android android-recyclerview recycler-adapter android-viewholder
source share
1 answer

In fact, I think the ViewHolder should be either a static nested class (mind static!) Or a top-level class (which will not actually be different, just the class name will contain the name of the outer class, followed by $ and then the name of the inner class )

Why do I think so? When ViewHolder is the non-stationary adapter inner class, it stores a reference to the adapter. Now, when you call RecyclerView.swapAdapter (newAdapter, false) (or is it true? I donโ€™t remember), the new adapter will use ViewHolders created by the old one. Since it is not possible to remove / clear such an implicit link in these holders, this link to the first adapter has leaked and cannot be garbage collected. This is bad.

But in my case, I had real non-memory issues. My adapter had a โ€œselection modelโ€ that kept the mapping between positions and data, and the view holder used the data when it displayed the item (for example, when the selection model indicated that the item at position 17 was selected when it was drawn on the screen, its color font will change) to mark it for the user. He did this by simply accessing the field of the adapter selection model, which in Java means that he uses an implicit reference to an instance of the incoming adapter and accesses his field. Now, after the swapAdapter, the saved ViewHolders still used the old adapter selection model, and the user interface was broken, because some elements were displayed as selected, while they were not in the new model.

Essentially, it is not possible for such non-static internal class owners to survive the adapter they created and used by others to really forget the old and use the new adapter, since there is no way to clear this implicit link.

There are many solutions, one of which is for the ViewHolder to be a static nested class and simply give it a reference to the adapter explicitly when it binds, and nullify it when it disappears. I use top-level classes for my view holders with explicit adapter links, which I think you are asking about. Keep in mind that very often owners do not need any links to their adapter at all, so you do not have to install the adapter at all.

Of course, my problem is that I changed the cursor; if you do not, you will probably never notice any problems, but I think it is best to be aware of them.

+7
source share

All Articles