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)?
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.
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);
TextView tv1 = (TextView)findViewById(R. id. textView1); tv1. setText("Hello"); setContentView(tv1);
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With