Afollestad sectionedRecyclerView. How to use separate ViewHolders for each element
I'm trying to implement this sectionedRecyclerView library in my application, but I need it to have cases where there are no section headers / footers (while items are showing) and cases where they are. This library always requires at least 1 section / title.
Also, this library only has one viewHodler. I want to be able to use different viewHolders for elements, headers and footers.
What methods will I need to override / change to accomplish this?
+3
source to share
1 answer
First, you must have a type variable in your model.
public class MyModel{
private int type;
//setters and getters...
}
Then create 2 viewnodes on your adapter, but the class you will be using in Adapter <> will be the main class (ViewHolder).
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
class ViewModel1 extends RecyclerView.ViewHolder{
//your code
}
class ViewModel2 extends RecyclerView.ViewHolder{
//your code
}
}
After that, you have to implement some methods on your adapter.
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<MyModel> mModelList;
public MyAdapter(List<MyModel> models){
this.mModelList = models;
}
@Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (viewType) {
case TYPE_1:
view = inflater.inflate(R.layout.view_type_1, parent, false);
return new ViewModel1(view);
case TYPE_2:
view = inflater.inflate(R.layout.view_type_2, parent, false);
return new ViewModel2(view);
}
return null;
}
@Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final MyModel item = mModelList.get(position);
switch (item.type) {
case TYPE_1:
final ViewHolder1 vh1 = (ViewHolder1)holder;
//your code
break;
case TYPE_2:
final ViewHolder2 vh2 = (ViewHolder2)holder;
//your code
break;
}
}
@Override public int getItemViewType(int position) {
return mModelList.get(position).type;
}
@Override public int getItemCount() {
return mModelList.size();
}
}
0
source to share