Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

without drawable
with drawable

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)?

like image 618
Jacob Avatar asked Jun 29 '12 12:06

Jacob


People also ask

How do you center text in TextView?

android:gravity="center" for text center in TextView. android:gravity="center_horizontal" inner text if you want horizontally centered. android:gravity="center_vertical" inner text if you want vertically centered. android:layout_centerInParent="true" if you want TextView in center position of parent view.

Which method is used to set the text in a TextView?

Set the Text of Android TextView Following is another way to set the text of textview control programmatically in activity file using setText() method. TextView tv = (TextView)findViewById(R. id. textView1);

Can we change the text in TextView?

TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);


2 Answers

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.

like image 139
blahdiblah Avatar answered Sep 22 '22 13:09

blahdiblah


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> 

This is what the result looks like.

like image 45
Rohan Taneja Avatar answered Sep 19 '22 13:09

Rohan Taneja