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

查看:40
本文介绍了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 assuming your RecyclerView fits the screen.

如果您想要更复杂的解决方案(自定义布局管理器,具有直接来自 XML 的每项控制和百分比通胀),请参阅 这个答案.

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

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

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