Answer the question
In order to leave comments, you need to log in
Android. Is using fragments in RecyclerView justified?
I have a card that, among other information, can contain an image, an image slider (3rd party library) or a video (YouTubeAPI). Previously, in the layout of the card, I simply indicated all three media elements (image, slider, video) and, depending on the needs, changed their visibility, hiding unnecessary elements and leaving only the necessary one visible.
Then I decided to try using fragments. I made three fragments, for each element (I note that the fragment class contains all the logic of the element, it only needs to pass parameters for initialization, and it will do the rest itself), and tried to use it in RecyclerView. If earlier I had three elements in the card, now I just wanted to put the fragment I needed in a special container in the card. But it was not there. In the onBindViewHolder of my RecyclerView adapter, this code replaces only the first element:
ImageSliderFragment fragment = ImageSliderFragment.newInstance(currentItem.images, mContext);
fragmentManager.beginTransaction().replace(R.id.card_media_container, fragment).commit();
Answer the question
In order to leave comments, you need to log in
There is no need to combine three Views into one fragment, since we RecyclerView
already have the following methods for creating and binding a ViewHolder:
and
The viewType parameter is what you need. Override the method
so that for each element of the adapter it returns the desired type (video / slider / image), in onCreateViewHolder() inflate the desired view depending on the type of view, and create a ViewHolder, and in onBindViewHolder() bind the desired element to the viewholder, in depending on the type of the element.
The solution to filling only the first element is to specify not the usual container id, but assign a unique id to the container of each element and insert a fragment into it.
The question of the appropriateness of using the fragment in this particular case remains open.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question