Reputation:
Displaying a certain layout for a card, when using CardView
, is simple enough.
I've created an XML layout for my card, and instantiate that XML layout to the View using LayoutInflater
.
More specifically:
View largeCardView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view, viewGroup, false);
Which is called in the onCreate()
method of my RecyclerAdapter
. The onCreate
method then returns this largeCardVew
. This works perfectly and the cards are displayed as they are laid out in the XML file.
But what if I want to display different cards for different content? Is it possible to show different cards for different things, but have them all in the same RecyclerView
?
For example, if I know before hand that there will be a string passed into a TextView
in the card, and this string can only have two values "Large" and "Small", how can I use one type of XML file to use with the "Large" text, and another XML file to use with the "Small" text?
Here is an example (taken from Google Play):
As you can see in the picture, there are two different card types, with different layouts (ignore the orange button). Is there a way to achieve a similar thing, and have the cards in the same RecyclerView
?
Upvotes: 4
Views: 1407
Reputation:
It's similar to how you would create a single card layout, but instead of having a single .xml
and a single ViewHolder
, each layout needs to have its own .xml
file defining it, and a ViewHolder
class.
The method which was found to be very important, is the getItemViewType(int position)
method in the RecyclerView.Adapter class. By default, this method returns 0, assuming a single layout for the viewType
being used (in this case, a cardView
). Since more than a single type is needed, I had to define them.
I then created an array of integers (called cardViewTypes
), defining which layouts get used for which type of data. Since you should already have some sort of dataset for the content of the cards (whether it's a List
or a HashMap
), it's important to make sure that the data matches up with the view types.
In my case, I wanted to have 4 different card layouts, so I defined each in their own .xml
file and gave them unique names. Then, in my RecyclerView.Adapter
class, I created a separate class which extended ViewHolder
for each layout. I made sure that each integer in my viewType
array matched up with my data and called getItemViewType
.
I then check the view type in the onCreateViewHolder
method of the RecyclerView.Adapter
, and inflate the corresponding view, which is then bound in onBindViewHolder(ViewHolder, int)
.
And the result is differing card layouts for different content.
Upvotes: 3