【问题标题】:LinearLayout horizontal orientation doesn't work for RecycleView elementsLinearLayout 水平方向不适用于 RecycleView 元素
【发布时间】:2021-02-24 11:17:36
【问题描述】:

我尝试在蚀刻线上将所有回收视图元素对齐 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>

我得到的结果:

【问题讨论】:

    标签: android xml android-linearlayout orientation


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 我按照你说的做了,首先在 XML 中更改 GridLayoutManager 不起作用。因为我有我的 rv.layoutManager 一个 LinearLayout 。但是在从 Kotlin 代码更改后它起作用了: rv.layoutManager = GridLayoutManager(this,2) 谢谢你的帮助!
    【解决方案2】:

    如果您想在 recyclerview 中并排设置 2 列中的项目,那么您必须使用 recyclerview 网格布局管理器。例如:android-gridlayoutmanager-example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 2017-04-28
      相关资源
      最近更新 更多