Home » Android » android – button text not getting centered vertically in button

android – button text not getting centered vertically in button

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am creating an Android app, and I have a button with a custom background image behind it. The background image is just a rectangle, but now the button text does not seem to be centered vertically. Here is my xml for the button:

<Button 
android:id="@+id/save_to_list"
android:layout_below="@+id/info_pic"
android:text="SAVE TO LIST"
android:textColor="@android:color/white"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_width="260dp"
android:layout_height="35dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"></Button>

and I set the background here:

ImageView button_bg = (ImageView)findViewById(R.id.button_background);
savetolist_button.setBackgroundDrawable(button_bg.getDrawable());

Is there a where to change the position of the text within a button?

How to&Answers:

android:layout_gravity defines layout alignment inside it’s parent. To align text within the button you need android:gravity, for example

<Button 
    ...
    android:gravity="center"
    ...>
</Button>

Answer:

Your button is too short to fit the text properly. Increase the layout_height and the text should be centered.

Answer:

Your text likely has some padding built into the font as part of each letter, and that is why your text is being pushed in one direction. Set the layout_height to “wrap_content” and your text should now be centered correctly.

Answer:

I found it best to use a 9 patch image for a rectangular background rather than an xml drawable.