Basically i can use multiple row on recyclerview adaper without any problem such as this code:
@Override
public ShowBookItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
switch (viewType) {
case 1:
layout = R.layout.item_heading_one;
break;
case 2:
layout = R.layout.item_heading_two;
break;
}
View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
ShowBookItemsViewHolder holder = new ShowBookItemsViewHolder(v);
return holder;
}
now i'm trying to use this feature when i'm using DataBinding, but i get an error and i can't do that
this is my wrong code:
@Override
public RobotViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
if (inflater == null) {
switch (viewType) {
case 0:
layout = R.layout.robot_item_action;
break;
case 1:
layout = R.layout.robot_user_action;
break;
}
inflater = LayoutInflater.from(parent.getContext());
}
RobotDataBinding dataBinding = RobotDataBinding.inflate(layout, parent, false);
return new RobotViewHolder(dataBinding);
}
You are trying to bind the adapter's views before its view holder is instantiated. View binding should be performed in onBindViewHolder().
Create a base view holder class that extends RecyclerView.ViewHolder
and has an abstract bind(Object obj) method that ShowBookItemsViewHolder
and RobotViewHolder
implement. Credit to George Mount for this approach.
public abstract class BaseViewHolder extends RecyclerView.ViewHolder {
...
// delegate binding to child class
protected abstract void bind(Object obj);
}
Then in onBindViewHolder()
:
public void onBindViewHolder(BaseViewHolder holder, int position) {
holder.bind(adapterData.get(position)
}
This will pass your adapterData object to the child view holder for binding:
public class ShowBookItemsViewHolder extends BaseViewHolder {
...
public void bind(Object obj) {
// Bind here...
}
}
Override getItemViewType()
to supply onCreateViewHolder()
with different view types. For example:
public int getItemViewType(int position) {
// Change layout every other position
return position % 2 == 0 ? 0 : 1;
}
Use the view type to construct the view holders:
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new ShowBookItemsViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false)
else {
return new RobotViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false)
}
}
Make sure onCreateViewHolder()
returns the base view holder and the adapter class extends RecyclerView.Adapter<YourAdapter.YourBaseViewHolder>
.