Android: Center aligning a TextView with drawableLeft

Instead of using a TextView and ImageView, we can use drawables of TextView to reduce the no.of views used.

So, the problem at hand is, how do you align a TextView text and it’s left drawable to the center horizontally in a given width.

Fail Method: 

Put the textview width to “match_parent” and use “android:gravity” as center, the expected result is that both drawable and text should be center aligned horizontally, but to my surprise, i see only text horizontally aligned and the drawable is aligned to the textview left.

Working Method But Not Efficient:

Take a horizontal LinearLayout, put ImageView and TextView(no drawableLeft since we are using ImageView) in it with each of the view’s width set to “wrap_content”, and use “android:layout_gravity” to center on the LinearLayout. This works but we are using extra ImageView and LinearLayout.

Best Method:

Set TextView’s width to “wrap_content”, use drawableLeft,  and set “layout_gravity” to center for the TextView.

Happy Coding…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s