0

I have a RecyclerView displaying a single textview I'd like centered.

My Activity Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

My recyclerview row layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/my_textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" />
</RelativeLayout>

The activity width fills the width of the screen, the recyclerview matches that width, the row RelativeLayout matches the recyclerview width, and the textview matches the RelativeLayout width. The gravity specified says to center the content of the textview horizontally. Therefore the text is centered across the width of the screen.

Why doesn't this logic work for LinearLayout? Change the row layout's root to LinearLayout and the gravity attribute isn't acknowledged.

Marc
  • 219
  • 1
  • 15

1 Answers1

1

Use android:layout_gravity="center" to center the textView relative to everything else. android:gravity="center" centers subviews. See here for more explanation.

Danny Michelin
  • 100
  • 1
  • 10
  • That does not work since the textview width fills the screen. gravity does not center "subviews", it centers content. In this case the gravity of the textview is the text content. If I had a viewgroup with gravity that would affect the content, which would be the subviews. – Marc Dec 03 '17 at 20:41