Home > Software engineering >  Android center_vertical gravity not works
Android center_vertical gravity not works

Time:11-20

Hello I am trying to make those tvGoldName and tvGoldValue to be height of ImageView from the left and be centered vertically. How to achieve that?

enter image description here

Here is my code:

    <LinearLayout
    android:id="@ id/llGold"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/llToNextLevel"
    android:orientation="horizontal"
    android:layout_gravity="center_vertical"
    android:weightSum="10">

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:gravity="right">

        <ImageView
            android:id="@ id/ivGoldIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingRight="10dp"
            android:src="@mipmap/coins"
            android:textColor="#FFFF00"
            android:textSize="21sp" />

        <TextView
            android:id="@ id/tvGoldName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/ivGoldIcon"

            android:gravity="right|center_vertical"
            android:paddingRight="10dp"
            android:text="@string/gold"
            android:textColor="#FFFF00"
            android:textSize="21sp" />

    </RelativeLayout>

    <TextView
        android:id="@ id/tvGoldValue"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:gravity="left"
        android:paddingRight="10dp"
        android:text="0"
        android:textSize="21sp" />

</LinearLayout>

CodePudding user response:

To make both have the same height as the ImageView:

As the tvGoldName is in RelativeLayout then align its top & bottom the the ImageView:

<TextView
    android:id="@ id/tvGoldName"
    android:layout_alignBottom="@ id/ivGoldIcon"
    android:layout_alignTop="@id/ivGoldIcon"

As the tvGoldValue is in the parent LinearLayout then:

make its height as match_parent, and align it vertically with center_vertical gravity:

<TextView
    android:gravity="center_vertical"
    android:gravity="center_vertical"
    android:layout_height="match_parent"

But in general, you should be using ConstraintLayout to have a flat design without nesting views; and as the RelativeLayout has performance issues.

  • Related