繁体   English   中英

如何将 RecyclerView 水平居中?

[英]How to center a RecyclerView horizontal?

只是试图将我的 RecyclerView 水平居中,但像 Gravity:"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

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

更好的解决方案是保持此代码并在用于 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM