简体   繁体   中英

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.

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

    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. [![image][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

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. Gravity property is for linearLayout. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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