Keep text in TextView with drawableLeft centered
In my app I have a header bar which consists of a single textview with fill_parent as width, which have a specific background color and some centered text. Now I want to add a drawable on the left side of the header bar, so I set the drawableLeft and sure enough the text and image is displayed. However the problem here is that the text is no longer properly centered, e.g., when the drawable is added the text is shifted a bit to the right as shown in the screenshots here:
Is there anyway I can center the text properly and have the drawable positioned as it is above without using an additional layout item (such as a LinearLayout)?
Solution 1:
Though fragile, you can avoid the use of a wrapper Layout by setting a negative padding on the drawable:
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:drawableLeft="@drawable/icon"
android:drawablePadding="-20sp"
android:text="blah blah blah" />
You'll have to adjust the padding to the width of the drawable, but you're left with just a single TextView instead of an extra LinearLayout or etc.
Solution 2:
You can set the parent of the TextView as a RelativeLayout whose width is match_parent.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/edit_location_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/add_location_text_view"
android:gravity="start|center_vertical"
android:layout_centerHorizontal="true"
android:drawableStart="@android:drawable/ic_menu_edit"
android:text="Edit Location" />
</RelativeLayout>
Solution 3:
I've faced a similar problem. Solved it by using single TextView
with layout_width="wrap_content"
and layout_gravity="center"
parameters:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/some_drawable"
android:text="some text"
android:layout_gravity="center"
android:gravity="center"
/>
Solution 4:
Try following:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:textAlignment="center" />
Solution 5:
You can use android:gravity="center_vertical"
to center the text vertically with the image. Or it can be centered inside the textView using android:gravity="center"
.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:drawableLeft="@drawable/icon"
android:text="Your text here" />