Should RecyclerView.ViewHolder always be an inner class?

I have two RecyclerView.Adapter that use the same RecyclerView.ViewHolder as inner classes.

I wanted to get rid of code duplication and made this ViewHolder free, separate class, so the new class can now be used by any RecyclerView.Adapter s.

However, I encountered many problems, for example, difficulties in accessing adapter objects. getAdapterPosition() always returns -1 .

So, I changed my mind and made a super RecyclerView.Adapter class that extends these adapters and puts the ViewHolder in a superclass so that these adapters can use it from a subclass.

But I want to know if ViewHolder should be an inner class. It annoys me. Please DO NOT advise me to combine adapter classes, they are completely different, since ViewHolder is just a special viewType that can appear in any RecyclerView

I look forward to your best approaches that make me feel better.

Sincerely.

+8
java android android-recyclerview android-viewholder
source share
3 answers

ViewHolder may be outside the class . The inner class is just an offer in all tutorials for RecyclerView, this is the best way if your ViewHolder should have access to all Adapter parameters, even those private ones, but any access relations or objects can be recreated by the access methods in Adapter and ViewHolder.

I created a stand-alone project using ViewHolder as an external class, look. Link to the repository - https://github.com/maciejsikora/outsideviewholder .

I also think that the cause of your problem is the fact that in the first version of the code, ViewHolder was an internal class and had access to properties, after changing to an external class, the code had to be reorganized, and as a result, all relations between ViewHolder and Adapter should be carefully verified.

Answer to the question: ViewHolder should not be an inner class, and your problems are caused by incorrect implementation of the code when using ViewHolder as an external class.

+3
source share

Actually, no .

First you need to understand why we need an inner class?

We need inner classes in which we want this functionality to have only a specific class. As we have a lot of inner class for many Listeners and Button onClick and many others.

Thus, we use the inner class for , making things private, short, and simple .

You can make this thing ( ViewHolder ) a separate class. But it will be inefficient, clear (if you make another class, it will add an extra class to your project) and an efficient way.

+4
source share

I always used it as an internal one. I understand your problem, and I also dealt with it for a while, and I think there is an answer to this post. The guy from this answer had problems with adapters.

Check it out here: https://stackoverflow.com/a/212618/

Your question is an interesting question;)

0
source share

All Articles