I have a requirement where i have a single recycler view which should be supported by multiple model classes. My recycler view will inflate multiple different layouts . So to inflate layout i have defined my onCreateViewholder like below :
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 1:
View v1 = inflater.inflate(R.layout.searchresultsrow1, parent, false);
viewHolder = new AppViewHolder(v1);
break;
case 2:
View v2 = inflater.inflate(R.layout.searchresultsrow2, parent, false);
viewHolder = new AppViewHolder(v2);
break;
return viewHolder
}
On bindview method i use instance of to determine holder type : `
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof AppViewHolder){
AppViewHolder vh1 = (AppViewHolder) holder;
vh1.appName.setText(Html.fromHtml(**appList**.get(position).getmAppName());
}
} else if (holder instanceof ContactViewHolder){
ContactViewHolder vh3 = (ContactViewHolder) holder; vh3.contactName.setText(Html.fromHtml(**contactList**.get(position).getContactName()));}
}`
Now i am clueless what to send on itemCount :
@Override
public int getItemCount() {
return ??;
}
Since my applist object type is different and contact list object type is different. I have tried with switch case in getItemCount but then it only returns the count of single list and displays results only for the particular list whereas i want results combined of both the list. If i send the addition of both the list , then i will encounter arrayindexoutofbounds exception. What approach can be used in this case ?
i want results combined of both the list:
Since you want both lists result in recyclerView, Create a List of type object and add all contents of both list to this list. Then in onBindViewHolder()
check for list.get(position) instanceOf YourClass
then carry on your operation based on type.
In getItemCount()
return the size of combined list.
Hope this helps.