How To Inflate Different Layout Using Same Recycle Adapter?
I am using wordAdapter class to recycle list view i want to inflate different layout on a give condition like if flag is equal to one than inflate activity_all layout and if flag i
Solution 1:
You can add this in onCreateViewHolder
section
@NonNull
@Override
public YouAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == 0)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_xml_one, parent, false);
return new v;
}else
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_xml_two, parent, false);
return new v;
}
}
Solution 2:
In your adapter class, you need to declare the type on the top like
private static final int VIEW_ITEM = 1;
private static final int LOADING = 0;
private static final int VIEW_TYPE_EMPTY = 2;
And in the onCreateViewHolder
you need to declare the ViewHolders like this
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder vh = null;
switch (viewType) {
case VIEW_TYPE_EMPTY:
View emptyView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_view_no_data, parent, false);
vh = new EmptyViewHolder(emptyView);
break;
case VIEW_ITEM:
View itemView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_view_game_details, parent, false);
vh = new GameViewHolder(itemView);
break;
case LOADING:
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.layout_progress_bar, parent, false);
vh = new ProgressViewHolder(v);
break;
}
return vh;
}
And in onBindViewHolder
you need to first check the instance of viewholder and the typecast according to the instance
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof GameViewHolder) {
/** You code for you ViewHlder**/
} else if (holder instanceof ProgressViewHolder) {
/** You code for you ViewHlder
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
**/
}
}
Post a Comment for "How To Inflate Different Layout Using Same Recycle Adapter?"