I need to create a recyclerView with a GridLayoutManager on two lines, and the first element to be bigger than the rest. The result should look like this:
I managed to achieve this, but in an unconventional way. In my recyclerView adapter I use a different viewHolder for the first element, a bigger one. That would have been a great solution, but the second element would have gone below the first element. So I made a trick of giving recyclerView a fixed height same as the first element, that way the first element and the second would overlap and I would simply make the visibility of the second to gone.
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0:
final View view = inflater.inflate(R.layout.big_item, parent, false);
return new BigViewHolder(view);
case 2:
final View view2 = inflater.inflate(R.layout.normal_item, parent, false);
return new NormalViewHolder(view2);
default:
return null;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (position == 1) {
holder.itemView.setVisibility(View.GONE);
}}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return 0;
} else return 2;
}
But I don't particularly like this approach. Does anyone have a better idea on this?
GridLayoutManager.SpanSizeLookup
. You can return a span of 2 for the first item, and 1 for the rest. – RoborantSpanSizeLookup
, and override thegetSpanSize(int position)
method toreturn 2;
forposition == 0
, andreturn 1;
for the rest. Then you set an instance of that on theGridLayoutManager
. You can do it all anonymously, like is common for anOnClickListener
. A quick example: drive.google.com/file/d/1K3HCdetp0M8vT8M55pOO0pr7aMWZHyjJ/…. – Roborant