【发布时间】:2019-06-21 20:09:23
【问题描述】:
如何获得具有网格布局的回收器视图,其中每个单元格具有相同的单元格宽度和单元格高度,具体取决于屏幕宽度。
我这样设置布局
linearLayoutManager = LinearLayoutManager(this)
categoriesRecyclerView.layoutManager = GridLayoutManager(this,4)
而且我总是连续获得 4 个单元格。
结果如下所示。
我明白为什么我会得到这个结果。我将单元格内的内容始终设置为wrap_content。所以当图片较大或文字较长时,高度会发生变化。
我的布局是这样定义的:
<androidx.constraintlayout.widget.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"
app:layout_constraintDimensionRatio="1:1"
android:layout_margin="8dp"
android:background="@drawable/rounded_image_view">
rounded_image_view 只是一个形状。
我认为我可以借助比率来调节约束布局。
我尝试过的其他一些事情:使用卡片,使用线性布局,将内容放在 View 中,与 constraintHeight_percent 合作,我在类似的主题中阅读了很多。但我没有得到解决方案。
完整的xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
app:layout_constraintDimensionRatio="1:1"
android:layout_margin="8dp"
app:layout_constraintHeight_percent="0.5"
android:background="@drawable/rounded_image_view">
<ImageView
android:id="@+id/categoryImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@id/itemTitle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/anatomie" />
<TextView
android:id="@+id/itemTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Anatomie"
android:textColor="@color/colorAccent"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/categoryImage" />
<ImageView
android:id="@+id/isPremiumImage"
android:layout_width="20dp"
android:layout_height="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/locked" />
</androidx.constraintlayout.widget.ConstraintLayout>
【问题讨论】:
标签: android xml kotlin android-constraintlayout android-gridlayout