如何居中GridLayoutManager的内容?

问题描述

只需尝试将RecyclerView水平居中。

这是xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">



    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent" 
        android:layout_height="match_parent"/>


</RelativeLayout>

这里是Java代码

mRecyclerView = findViewById(R.id.recycler_view);
itemLayoutManager = new GridLayoutManager(this,6);
mRecyclerView.setLayoutManager(itemLayoutManager);
...
mItemAdapter = new ItemAdapter(MainActivity.this,mItemList);
mRecyclerView.setAdapter(mItemAdapter);

当我运行应用程序时,recyclerview会向左对齐。 我该怎么做才能使内容居中,以使左右边距与右侧示例图片中的边距相同?

enter image description here

解决方法

创建一个类,将填充设置为项目:

class SpacingItemDecorator (private val padding: Int) : RecyclerView.ItemDecoration()
{
    override fun getItemOffsets(
        outRect: Rect,view: View,parent: RecyclerView,state: RecyclerView.State
    )
    {
        super.getItemOffsets(outRect,view,parent,state)
        outRect.top = padding
        outRect.bottom = padding
        outRect.left = padding
        outRect.right = padding
    }
}

现在您的RecyclerView中设置了paddingStartpaddingEnd,例如4dp

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingStart="4dp"
    android:paddingEnd="4dp"
    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    app:spanCount="6"/>

创建适配器时,只需应用此项目装饰器即可:

val x = (resources.displayMetrics.density * 4).toInt() //converting dp to pixels
recyclerView.addItemDecoration(SpacingItemDecorator(x)) //setting space between items in RecyclerView

RecyclerView项目:

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="6dp"
    app:cardElevation="4dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/txtContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{Integer.toString(dataView.id)}"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

结果:

enter image description here