RecyclerView项目中的Android屏幕宽度百分比 [英] Android percent screen width in RecyclerView item

查看:512
本文介绍了RecyclerView项目中的Android屏幕宽度百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将RecyclerView的项目高度设置为屏幕高度的30%?

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

我不能简单地使用ConstraintLayout或PercentFrameLayout/PercentRelativeLayout,因为这些位置的子布局相对于父布局而言,其尺寸可能与屏幕不匹配.

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.

最好,我希望以纯XML格式执行此操作(而不必使用任何Runnable来动态获取屏幕高度).

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

编辑

需要澄清的是,由于许多解决方案都建议限制RecyclerView的高度,所以这并不是目的. RecyclerView仍应填充屏幕.这就是我在说的,使用屏幕宽度(而不是高度):

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):

想法是使卡的宽度为屏幕宽度的33%,同时保持RecyclerView的宽度在水平滚动超过屏幕时保持不变.

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.

推荐答案

您可以覆盖RecyclerView用来强制指定大小的LayoutManager方法之一:

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;
    }
});

这是为了让您的RecyclerView适合屏幕.

This is assumiing your RecyclerView fits the screen.

这篇关于RecyclerView项目中的Android屏幕宽度百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆