How to vertically align text in a TextView with Compound Drawable

Nick Fanelli picture Nick Fanelli · Sep 11, 2014 · Viewed 8.7k times · Source

This question is in a way a continuation of my last question.

My problem now is pretty much the same, except that instead of separating the image and text in differend views (namely ImageView and TextView) I learned I can use the attribute android:drawableLeft to set an image "for" my text (the suggestion was pointed to me by Eclipse with a warning icon on the LinearLayout line).

I thought the only difference would be that instead of setting the ImageView with setImageResource() method I would simply set the TextView's drawableLeft attributed with the setCompoundDrawablesWithIntrinsicBounds() method. Instead, when I made the change, I was taken back to my original issue: the text aligns with the top edge of the view rather than the center.

This is what my TextView looks like:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >       
    <TextView 
        android:id="@+id/account_login"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/pm_gmail"
        android:drawablePadding="8dp"
        android:text="[email protected]"
        android:paddingLeft="16dp"
        android:layout_gravity="left|center_vertical" />

    <View
        android:layout_width="fill_parent"
        android:layout_height="1dip"
        android:layout_centerVertical="true"
        android:layout_below="@id/account_login"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="5dp"
        android:background="#DDDDDD" />

</RelativeLayout>

The second View is just a separator.

... and this is what the layout looks like after setting the above mentioned attributes: (I don't have enough reputation to post images yet, so here's the link to it)

(Just to be clear, this is only a static example. My text and image are both set dynamically in the code at runtime).

Any help is greatly appreciated.

Answer

Phant&#244;maxx picture Phantômaxx · Sep 11, 2014

Change android:layout_gravity="left|center_vertical" to android:gravity="center_vertical".
layout_gravity is for positioning a View inside a container (layout), while gravity is referred to the View contents (that is, in this case, the text inside the TextView).