Basically i can use multiple row on recyclerview adaper without any problem such as this code:
@Override
public ShowBookItemsViewHolder onCreateViewHolder(Vi
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>
.