Centering the TextView's text vertically in relation to its drawableLeft image
AndroidAndroid LayoutAndroid WidgetAndroid Problem Overview
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?
Android Solutions
Solution 1 - Android
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" />
Solution 2 - Android
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"
Solution 3 - Android
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.
Solution 4 - Android
You should place both the Drawable
and the TextView
inside a RelativeLayout
and use the layout_alignBaseline
attribute on your TextView
.
You could also place just the two items, Drawable
and TextView
inside a LinearLayout
with a horizontal
orientation and layout_height="wrap_content"
and use layout_gravity="center_vertical"
on your TextView
.