I'm trying to use RecyclerView and GridLayoutManager to display a list of items.
Here are the criteria which I want to satisfy:
- Each row has a number of items specified by
spanCount
- Each item takes up an equal portion of the screen and together they fill up the whole screen.
- An item height is determined by its width and a specified ratio.
I found that if I set android:layout_width="match_parent"
on the item view, then the item width will be set by dividing RecyclerView's width by spanCount
.
The problem is that I don't know to make item height proportional to its width as determined by the layout manager.
My only solution is to forego layout manager for measurements, and to explicitly set item dimensions in onBindViewHolder
:
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
ViewGroup.LayoutParams p = v.getLayoutParams();
p.width = parent.getWidth() / mLayoutManager.getSpanCount();
p.height = p.width * 3/2;
v.setLayoutParams(p);
return new MyViewHolder(v);
}
I will appreciate any pointers which will help me improve my solution.