首页 > 解决方案 > 如何使 RecyclerView 水平居中?

问题描述

只是试图将我的 RecyclerView 水平居中,但像重力:“center”或 layout_centerHorizo​​ntal="true" 这样的线条不起作用。

这是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, 3);
    mRecyclerView.setLayoutManager(itemLayoutManager);
    ...
    mItemAdapter = new ItemAdapter(MainActivity.this, mItemList);
    mRecyclerView.setAdapter(mItemAdapter);

当我运行应用程序时,recyclerview 左对齐。[![图片][1]][1]

我究竟需要做什么才能使内容居中以使左右边距相同?谢谢。[1]:https ://i.stack.imgur.com/0LNoY.png

标签: javaandroidgridviewandroid-recyclerview

解决方案


它不居中,因为 layout_width 都是 match_parrent 尝试在 recyclerview 上使用 wrap_content 并在 recyclerview 上使用 layout_centerHorizo​​ntal=true 。重力属性用于线性布局。更多你为什么使用网格布局管理器?

更好的解决方案是以这种方式保留此代码,并在用于 RecyclerView 的行上将图像设置在行的中心:例如

行布局:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
   <ImageView
     android:layout_width="100dp"
     android:layout_height="100dp"
     android:layout_gravity="center_horizontal"/>
</LinearLayout>

对于布局管理器,如果您不使用这两列,请使用 LinearLayoutManager


推荐阅读