user3476555
user3476555

Reputation: 41

How to android text alignment in a button when gravity:center is not working

I have the following :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical" >
 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:gravity="left|center_vertical" />

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Text"
    android:gravity="left|center_vertical" />

</LinearLayout

I want to get my button's text to align left. Right now its aligned in the center. The textview's text is aligned left without any problems. Is there something else I need to add? I don't really have to close and reopen my IDE because I use maven to build. Any suggestions?

ANSWER

Figured it out : set android:paddingLeft="0dp" . Done. No need for gravity there.

Upvotes: 0

Views: 2680

Answers (2)

Brayden Willenborg
Brayden Willenborg

Reputation: 71

When you set an object's gravity property, you're telling that object where you want its contents to be aligned. In your code, you're trying to align the text in a box that only as big as the text itself, which does nothing.

There are 2 ways to solve this problem.

A) You can set the button's width to be not wrap the content.

<Button
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="Button"
    android:gravity="left|center_vertical" />

B) You can set the width of the text-view to not be wrap content.

<TextView 
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="Text"
    android:gravity="left|center_vertical" />

Otherwise, what you're doing right now should have some text in a button where there is no space between the edge of the text and the outside of the button. If there is space there, make sure you're not setting padding or margins in the button or text.

Upvotes: 0

Kunu
Kunu

Reputation: 5134

Instead of wrap_content give some value. Actually its working but you can't see because your width is set as wrap_content

<Button
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="Button"
    android:gravity="left|center_vertical" />

Upvotes: 1

Related Questions