I have a RecyclerView. In adapter I have a boolean flag to determine which of layout should be used for all items:
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
private boolean mIsSecondModeEnabled;
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(mIsSecondModeEnabled ?
R.layout.layout_second_mode_item :
R.layout.layout_first_mode_item, parent, false);
return new MyHolder(view);
}
public void setModeEnabled(boolean enabled) {
mIsSecondModeEnabled = enabled;
notifyDataSetChanged();
}
}
This code doesn't work completely right. When I call setModeEnabled(true)
some items showing with layout_first_mode_item
layout.
How to achieve it?
onCreateViewHolder()
will be called, when there are no ViewHolder
s in the pool of already created ViewHolder
s. In this callback you specify what view you want RecyclerView
to create for you.
onCreateViewHolder()
will not necessarily be called after you have performed notifyDataSetChanged()
. Instead onBindViewHolder()
will be triggered. This is the place where you should update your view.
Override getItemViewType()
and return the layout id depending on your use case:
@Override
public int getItemViewType(final int position) {
return mIsSecondModeEnabled ? R.layout.my_layout_1 : R.layout.my_layout_2;
}
Create 2 ViewHolder
classes for those two layouts and from onCreateViewHolder()
return appropriate ViewHolder
depending on the viewType
parameter of onCreateViewHolder()
callback.
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == R.layout.my_layout_1) {
// create FirstViewHolder
} else if (viewType == R.layout.my_layout_2) {
// create SecondViewHolder
}
// return created ViewHolder
}
Then in onBindViewHolder()
callback setup your views.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With