Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android percent screen width in RecyclerView item

How would I get a RecyclerView's item height to be, say, 30% of the screen's height?

I can't simply use a ConstraintLayout or a PercentFrameLayout/PercentRelativeLayout, since those position child layouts relative to parent layouts, whose size might not match the screens.

Preferably, I'd like to do this in pure XML (and not have to use any Runnables to get the screen height dynamically).

EDIT

To clarify, since a lot of solutions suggest restraining the height of the RecyclerView, that's not the intent. The RecyclerView should still populate the screen. Here's what I'm talking about, using the screen width (instead of height):

enter image description here

The idea is to get the card's width to be 33% the screen's width, while keeping the RecyclerView's width unaltered as it scrolls past the screen horizontally.

like image 583
davidchuyaya Avatar asked Jul 06 '18 00:07

davidchuyaya


People also ask

How do I reduce space between items in RecyclerView?

Try to use cardElevation=0dp. This should remove the extra spacing between recyclerview items.

What is Item view in RecyclerView?

A RecyclerView. ViewHolder class which caches views associated with the default Preference layouts. A ViewHolder describes an item view and metadata about its place within the RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive findViewById results.


1 Answers

You can override one of the LayoutManager methods used by your RecyclerView to force specific size:

recyclerView.setLayoutManager(new LinearLayoutManager(this){     @Override     public boolean checkLayoutParams(RecyclerView.LayoutParams lp) {         // force height of viewHolder here, this will override layout_height from xml         lp.height = getHeight() / 3;         return true;     } }); 

This is assuming your RecyclerView fits the screen.

If you want more complex solution (custom layout manager with per-item control & percent inflation straight from from XML) see this answer.

like image 106
Pawel Avatar answered Sep 23 '22 16:09

Pawel