简体   繁体   English

如何将 RecyclerView 水平居中?

[英]How to center a RecyclerView horizontal?

Just trying to center my RecyclerView horizontal but lines like gravity:"center" or layout_centerHorizontal="true" does not work.只是试图将我的 RecyclerView 水平居中,但像 Gravity:"center" 或 layout_centerHorizo​​ntal="true" 这样的线条不起作用。

Here is the xml:这是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>

And here the java code:这里是java代码:

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

When I run the application the recyclerview aligns left.当我运行应用程序时,recyclerview 左对齐。 [![image][1]][1] [![图像][1]][1]

What exactly do I have to do to center the content so that the margin is the same left and right?我到底该怎么做才能使内容居中,以便左右边距相同? Thanks.谢谢。 [1]: https://i.stack.imgur.com/0LNoY.png [1]: https : //i.stack.imgur.com/0LNoY.png

It does not center because both layout_width are match_parrent try using wrap_content on the recyclerview and layout_centerHorizontal=true on the recyclerview too.它不居中,因为 layout_width 都是 match_parrent 尝试在 recyclerview 上使用 wrap_content ,也在 recyclerview 上使用 layout_centerHorizo​​ntal=true 。 Gravity property is for linearLayout. Gravity 属性用于线性布局。 More why are you using the grid layout manager?更多你为什么使用网格布局管理器?

Better solution is to keep this code this way and on the row used for the RecyclerView set the image in the center of the row: eg更好的解决方案是保持此代码并在用于 RecyclerView 的行上将图像设置在行的中心:例如

RowLayout:行布局:

<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>

For Layout manager use LinearLayoutManager if you are not using those two columns对于布局管理器,如果您不使用这两列,请使用 LinearLayoutManager

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

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