Search code examples
androidlayoutandroid-linearlayoutcentering

Linear Layout centeralization


I'm having some problems with my LinearLayout centeralization, here goes a piece of my xml layout:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="300dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_payment_card_numbers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:visibility="gone"
        >

    </android.support.v7.widget.RecyclerView>

    <TextView
        android:layout_gravity="center_horizontal|center_vertical"
        android:textSize="@dimen/secondary_text"
        android:text="You have no credit cards"
        android:textStyle="italic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

I got that layout as result:

enter image description here

But I would like to center my text message vertically. Any idea?


Solution

  • The most important thing is to make your TextView match your parent's height. If its set to wrap_content then it won't be able to come at center as there is no vertical height for the TextView.

    Just use this TextView code -

    <TextView
    android:layout_gravity="center_horizontal|center_vertical"
    android:textSize="12sp"
    android:gravity="fill_vertical"
    android:text="You have no credit cards"
    android:textStyle="italic"
    android:layout_width="wrap_content"
    android:layout_height="match_parent" />
    

    I've added android:gravity="fill_vertical" and made android:layout_height="match_parent"