Lambda
Lambda

Reputation: 1

Why gravity doesn't center all of my views?

I was expecting all my TextView to be vertically centered in my RelativeLayout but this is only the case for the logo one. The others are anchored to the top of the latter.

Image

Here's my 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="72dp"
android:gravity="center_vertical">

<TextView
    android:id="@+id/logo"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:text="TextView" />

<TextView
    android:id="@+id/stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@+id/logo"
    android:layout_toRightOf="@+id/logo"
    android:text="TextView" />

<TextView
    android:id="@+id/eta"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@+id/stop"
    android:layout_toRightOf="@+id/stop"
    android:text="TextView" />

<TextView
    android:id="@+id/direction"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/stop"
    android:layout_toEndOf="@+id/logo"
    android:layout_toRightOf="@+id/logo"
    android:text="TextView" />

Upvotes: 0

Views: 35

Answers (1)

trylimits
trylimits

Reputation: 2575

The attribute layout_toEndOf performs layouting as follows:

Positions the start edge of this view to the end of the given anchor view ID. Link

Which means that all your TextViews start edges align with the logo's end. As a starting point, just remove all layout_toEndOf attributes.

Then your layout should look something like this:

+--------------+
|              | +-----------+
|              | |   stop    |
|              | +-----------+ +-----------+
|     logo     |/* no space */ |    eta    |
|              | +-----------+ +-----------+
|              | | direction |
|              | +-----------+
+--------------+

More precisely, logo is vertically centered, same as eta. Since your layout code explictly places stop and direction directly to the right of logo, therefore direction is below stop.

Upvotes: 1

Related Questions