Question:
I have an array of CardView which I am loading into the RecyclerView.
I want to separate this card with my element, I don’t understand how this can be done.
For example:
RecyclerView
Heading1, button with action
CardView
CardView
CardView
Heading2, button with action
CardView
CardView
CardView
Title3, button with action
CardView
CardView
CardView
RecyclerView
Answer:
You need to determine its type by the position of the element and, depending on this, load certain markup and display it:
//метод, в коем вы должны в зависимости от позиции элемента возвращать
//её тип в виде числа, кое потом используется в onCreateViewHolder для загрузки разметки
//и в onBindViewHolder для наполнения её данными
@Override
public int getItemViewType(int position)
{
if (position == 0)
{
return 0;
}
else
{
return 1;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
RecyclerView.ViewHolder vh;
View itemLayoutView;
//загружаем разметку в зависимости от типа и возвращаем
//нужный холдер
switch (viewType)
{
case 0:
itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.zero_type_layout, parent, false);
vh = new HolderZeroType(itemLayoutView);
break;
case 1:
itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.first_type_layout, parent, false);
vh = new HolderFirstType(itemLayoutView);
break;
}
return vh;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position)
{
switch (this.getItemViewType(position))
{
case 0:
HolderZeroType zero = (HolderZeroType) holder;
//наполняем данными разметку для нулевого типа
break;
case 1:
HolderFirstType first = (HolderFirstType) holder;
//наполняем данными разметку для нулевого типа
break;
}
}
public static class HolderFirstType extends RecyclerView.ViewHolder
{
...
public ViewHolderText(View v)
{
super(v);
...
}
}
public static class HolderZeroType extends RecyclerView.ViewHolder
{
...
public ViewHolderText(View v)
{
super(v);
...
}
}