Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering the TextView's text vertically in relation to its drawableLeft image

I have this component:

<TextView
    android:id="@+id/item_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/icon" />

The image in the drawableLeft attribute is bigger than the font of the text, so I want the text centered vertically in relation to the image. How can I get this effect?

like image 670
user940016 Avatar asked Mar 30 '12 19:03

user940016


3 Answers

You want "gravity" note this is not to be confused with layout gravity, layout gravity moves the entire textview, while gravity moves the text within the text view.

<TextView
    android:id="@+id/item_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableStart="@drawable/icon"
    android:gravity="center_vertical" />
like image 157
Martin Sykes Avatar answered Sep 25 '22 12:09

Martin Sykes


In addition to setting the gravity, this can also help with alignment in some situations by reducing paddings on the top and bottom of the textview, which can be unequal:

android:includeFontPadding="false"
like image 27
Learn OpenGL ES Avatar answered Sep 22 '22 12:09

Learn OpenGL ES


If you don't care about text accents, just try android:includeFontPadding="false".This will remove extra top and bottom padding of TextView. As to android:gravity="center_vertical", it has no effect on my code.

like image 20
shengming Avatar answered Sep 21 '22 12:09

shengming