RecyclerView中的ImageView不能“对齐”水平对齐

时间:2020-05-02 11:28:21

标签: android android-layout android-recyclerview

这是预览和设备上的外观。

Rows with different spacing

行布局和RecyclerView布局的代码是基础

行只有一个ImageView:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "175dp"
    android:layout_height = "175dp"
    android:layout_margin = "4dp">

    <ImageView
        android:id = "@+id/imageView"
        android:layout_width = "0dp"
        android:layout_height = "0dp"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent"
        tools:ignore = "ContentDescription"
        tools:srcCompat = "@tools:sample/avatars" />
</androidx.constraintlayout.widget.ConstraintLayout>

RecyclerView(该片段中的唯一视图)是一个具有2个跨度的网格:

    <androidx.recyclerview.widget.RecyclerView
        android:id = "@+id/recyclerView"
        android:layout_width = "0dp"
        android:layout_height = "0dp"
        app:layoutManager = "androidx.recyclerview.widget.GridLayoutManager"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent"
        app:spanCount = "2"
        tools:listitem = "@layout/row_dir_observer_secondary" />

我不知道出了什么问题,尝试了所有与重力相关的布局设置,尝试了权重,但是唯一的有效方法就是给父级添加padding_start。

2 个答案:

答案 0 :(得分:1)

您已经在适配器中使用了硬编码宽度,使用了match_parent,我认为您已经在使用span = 2的gridlayoutmanager,因此不需要在那里进行任何更改。

答案 1 :(得分:1)

当您在RecyclerView中将GridLayoutManager用作LayoutManager时,请不要设置固定大小的宽度,因为如果您希望RecyclerView的每个项目都具有相同的宽度,则GridLayoutManager会根据{{1} },如果您将width用作match_parent。

因此,首先从适配器的布局文件中删除硬编码的宽度值(此处示例为175dp),然后在Adpater布局文件中将其设置为match_parent宽度。

尝试一下,

SpanCout