首页 > 解决方案 > LinearLayout 水平方向不适用于 RecycleView 元素

问题描述

我尝试在蚀刻线上将所有回收视图元素对齐 2,但它们仅垂直对齐线上的一个元素。

这是我的代码:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
    android:id="@+id/card_pdf"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="12dp"
    android:layout_marginTop="12dp"
    android:layout_marginEnd="12dp"
    android:layout_marginBottom="12dp"
    android:layout_weight="1">
<TextView
android:id="@+id/tv_pdf_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ceva"
android:textSize="25sp"
android:padding="6dp"/>
</androidx.cardview.widget.CardView>
</LinearLayout>

结果我得到: 元素非常对齐

标签: androidxmlandroid-linearlayoutorientation

解决方案


您似乎不了解 RecyclerView 的概念或概念。一个 ViewHolder 仅包含 1 个项目(因此您创建的布局仅影响一个 ViewHolder,而不影响整个 RecyclerView,您将永远无法实现您想要的)。

相反,将这些行添加到 xml 中的您的 RecyclerView:

app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"

GridLayoutManager在网格中布置项目。spanCount定义该网格中有多少列。

您的项目布局中也不需要 a LinearLayout。你应该只有CardViewTextView


推荐阅读