【问题标题】:Android - How to keep column width for a RecyclerView item fixed while switching orientations?Android - 如何在切换方向时保持 RecyclerView 项目的列宽固定?
【发布时间】:2017-03-22 02:14:47
【问题描述】:

我正在尝试一个非常简单的应用程序,它使用带有 GridLayoutManager 的 RecyclerView。我想要实现的是保持卡片项目的列宽并更改它们之间的边距(我需要保持列宽固定)。但是,当我在纵向和横向之间切换时,列本身的宽度会发生变化。

如果我理解正确,我需要测量屏幕宽度除以每张卡片的宽度,并将 GridLayoutManager 的跨度计数设置为计算值。但我似乎遗漏了什么。

另外,我尝试使用 AutoFitRecyclerView (http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html) 并且有很多帖子 RecyclerView GridLayoutManager: how to auto-detect span count?Changing number of columns in RecyclerView gridlayout 有助于自动检测跨度计数,但这不是我想要实现的。我希望在调整列之间的边距时具有相同的列宽。

任何指针或解决方案将不胜感激。

这是网格项的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="210dp"
    android:layout_height="338dp"
    android:layout_margin="12dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/thumbnail"
            android:layout_width="match_parent"
            android:layout_height="270dp"
            android:background="#1F000000"/>

        <TextView
            android:id="@+id/title_text"
            android:layout_width="164dp"
            android:layout_height="wrap_content"
            android:layout_below="@id/thumbnail"
            android:layout_marginBottom="13dp"
            android:layout_marginLeft="13dp"
            android:layout_marginRight="32dp"
            android:layout_marginTop="13dp"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#393c3d"
            android:textSize="14sp" />
    </RelativeLayout>

</android.support.v7.widget.CardView>

【问题讨论】:

  • 发布布局?
  • @Shmuel 我刚刚添加了 GridItem 的布局,无论方向如何,我都想保留 CardView 的宽度和高度。有一个 12dp 的边距,不应该是不应该固定的。

标签: android android-recyclerview


【解决方案1】:

也许你可以重写 CardView 的 onMeasure 方法,将MeasuredDimension 设置为 210dp 和 338dp ,这样 Recyclerview 计算你的 Cardview 的宽度和高度时,它会返回绝对宽度和高度。

【讨论】:

    猜你喜欢
    • 2019-09-06
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多