【问题标题】:RecyclerView + GridLayoutManager: Resizing items to fit the screen and preserve ratioRecyclerView + GridLayoutManager:调整项目大小以适应屏幕并保持比例
【发布时间】:2018-02-22 08:53:12
【问题描述】:

我正在尝试使用 RecyclerView 和 GridLayoutManager 来显示项目列表。

以下是我想要满足的标准:

  • 每一行都有spanCount指定的项目数
  • 每个项目占据屏幕的相等部分,它们一起填满整个屏幕。
  • 项目的高度由其宽度和指定的比例决定。

我发现如果我在项目视图上设置android:layout_width="match_parent",那么项目宽度将通过将RecyclerView的宽度除以spanCount来设置。

问题是我不知道让项目的高度与布局管理器确定的宽度成正比。

我唯一的解决方案是放弃布局管理器进行测量,并在onBindViewHolder 中明确设置项目尺寸:

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_layout, parent, false);

    ViewGroup.LayoutParams p = v.getLayoutParams();

    p.width = parent.getWidth() / mLayoutManager.getSpanCount();
    p.height = p.width * 3/2;

    v.setLayoutParams(p);

    return new MyViewHolder(v);
}

我将不胜感激任何可以帮助我改进解决方案的建议。

【问题讨论】:

    标签: android android-recyclerview gridlayoutmanager


    【解决方案1】:

    item_layout xml 中使用ConstraintLayout 怎么样。 约束布局允许您将高度设置为宽度的比率。

    例如:

        <android.support.constraint.ConstraintLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <FrameLayout
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:layout_constraintDimensionRatio="3:2"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"/>
    
        </android.support.constraint.ConstraintLayout>
    

    所以当你使用app:layout_constraintDimensionRatio="3:2" 您正在设置 3 宽 2 高的比例。

    无论跨度数如何,这都应该有效

    【讨论】:

    • 好的,例如我为 Android TV 开发应用程序,在我的变体应用程序中:layout_constraintDimensionRatio 是 16:9。但是当电视有 16:10 或 4:3 时会怎样?
    • 在尝试了其他所有方法之后,这对我的情况实际上有所帮助。
    • 我在这里也提出了类似的建议:stackoverflow.com/a/64619615/835883
    猜你喜欢
    • 2013-07-11
    • 2018-09-16
    • 1970-01-01
    • 2018-03-01
    • 2023-01-12
    • 2011-02-03
    • 1970-01-01
    • 2015-08-31
    相关资源
    最近更新 更多