【问题标题】:How to center a RecyclerView horizontal?如何使 RecyclerView 水平居中?
【发布时间】:2020-09-10 19:32:44
【问题描述】:

只是试图让我的 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

【问题讨论】:

    标签: java android gridview android-recyclerview


    【解决方案1】:

    它不居中,因为 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多