Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/51201482/android-percent-screen-width-in-recyclerview-item

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...