如何将“回收者视图”的项目居中?

时间:2020-07-08 07:14:29

标签: android text android-recyclerview alignment

我设法制作了RecyclerView列表,但是无法将文本居中。下面是代码:

RecyclerView:

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="200dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

项目:

<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="wrap_content"
    android:layout_height="wrap_content"
    >

    <TextView
        android:id="@+id/listItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/caviar_dreams"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:paddingBottom="15dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

我尝试了所有我可以找到的属性,alignText,gravity,alignLayout等

2 个答案:

答案 0 :(得分:1)

只需将项目布局根元素的宽度属性从wrap_content更改为match_parent,以便每个行项目都占据RecyclerView的完整宽度,子文本将能够以该宽度为中心:

<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" // this is the change you have to make
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/listItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/caviar_dreams"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:paddingBottom="15dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

答案 1 :(得分:0)

在项目布局中,只需使用:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        .../>

</LinearLayout>

enter image description here