How can I use layout_weight in RecyclerView or ListView item view to have items of equal height fill up the available space on screen?
As the API reference says, layout_weight
is an attribute of LinearLayout
, so it cannot be used with other ViewGroups like, for instance, RecyclerView
and ListView
. Instead, you have to set the item's height programmatically.
Since you seem worried about your code's cleanliness, I think this is a rather elegant solution in case you use a RecyclerView
:
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.item_list, null);
int height = parent.getMeasuredHeight() / 4;
int width = parent.getMeasuredWidth();
view.setLayoutParams(new RecyclerView.LayoutParams(width, height));
return new ViewHolder(view);
}
Try this, work for me
int weight = 3; //number of parts in the recycler view.
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent,false);
rowView.getLayoutParams().height = parent.getHeight() / weight;
return new ViewHolder(rowView);
}