简体   繁体   English

如何使 Grid RecyclerView 项目居中?

[英]How to center Grid RecyclerView items?

I have a recycler view using grid layout manager.我有一个使用网格布局管理器的回收视图。 I did my item view to have the witdh = match_parent to make my items to have equal width depending on the screen width.我做了我的项目视图,让 witdh = match_parent 使我的项目根据屏幕宽度具有相等的宽度。 But there is also constraint which is max width for my item view.但也有一个约束,即我的项目视图的最大宽度。 So, if the span count is small, all my items are aligned by the left, but I want those items to be aligned by the center.所以,如果跨度计数很小,我所有的项目都靠左对齐,但我希望这些项目靠中心对齐。

Examples:例子: 1个

In case 1, everything is ok.在情况 1 中,一切正常。 In case 2, items are not centered.在情况 2 中,项目未居中。 PS I tried layout_gravity = center, gravity = center, it does not help PS 我试过 layout_gravity = center, gravity = center, 没有用

Try this out.试试这个。

<?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"
    android:gravity="center" >

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/question_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f0f4fd" 
        android:layout_gravity="center"
        android:layout_centerInParent="true"/>

</RelativeLayout>

In the row's xml, it is necessary to align the elements to the center在行的xml中,需要将元素居中对齐

In your item layout, don't use wrap_content , or a fixed size, in layout_width .在项目布局中,不要在layout_width中使用wrap_content或固定大小。 You should use match_parent as layout_width .您应该使用match_parent作为layout_width

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

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