Adding Multiple Different Cardviews To Recyclerview
Solution 1:
You can pass an ArrayList to your Adapter. This ArrayList represent a list of your data. In your adapter you have just to know with getType() which cardView to show. So for example :
YourAdapter(datas ArrayList<YourData>(),...){
onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int){
val type = getItemViewType(position)
if(type == 0){
//show cardview1YourViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.cardview1, parent, false))
}
if(type == 1){
YourViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.cardview2, parent, false))
}
}
@overridepublicIntgetItemViewType(int position){
return datas[position].type;
}
}
After YourData has to have a method type ( for this example). And you can add 3 elements of type 0 , after 2 elements of type 1 ... in the arraylist.
Sorry because there's a mix between kotlin and Java ( but I think you can understand)
Solution 2:
You can achieve it by this way
Firstly Add 3 Integer variables in your Model class name type
ITEM_TYPE_1 and
ITEM_TYPE_2. Assign a value to type
According to your need. like ITEM_TYPE_1 or ITEM_TYPE_2 respectively for view type 1 and view type 2.
publicclassModel{
StringSmsAddress;
StringKoreaImage;
String seasonNumber;
Integertype;
publicstatic final IntegerITEM_TYPE_1=1;
publicstatic final IntegerITEM_TYPE_2=2;
publicStringgetSmsAddress() {
returnSmsAddress;
}
publicvoidsetSmsAddress(String smsAddress) {
SmsAddress = smsAddress;
}
publicStringgetKoreaImage() {
returnKoreaImage;
}
publicvoidsetKoreaImage(String koreaImage) {
KoreaImage = koreaImage;
}
publicStringgetSeasonNumber() {
return seasonNumber;
}
publicvoidsetSeasonNumber(String seasonNumber) {
this.seasonNumber = seasonNumber;
}
publicIntegergetType() {
returntype;
}
publicvoidsetType(Integer type) {
this.type = type;
}
}
At your Adapter you can override
getItemViewType()
andonCreateViewHolder
() methods and apply a switch case for view inflation and Data Presentation through ViewHolders.
@Override
publicintgetItemViewType(int position) {
switch (modelList.get(position).getType()) {
case0:
return Model.ITEM_TYPE_1;
case1:
return Model.ITEM_TYPE_2;
default:
return-1;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case Model.ITEM_TYPE_1:
view = LayoutInflater.from(mContext).inflate(R.layout.item_type_1, parent, false);
return (new Item1ViewHolder(view));
case Model.ITEM_TYPE_2:
view = LayoutInflater.from(mContext).inflate(R.layout.item_type_2, parent, false);
return (new Item2ViewHolder(view));
default:
returnnull;
}
}
For More Detail see the link below:
Post a Comment for "Adding Multiple Different Cardviews To Recyclerview"