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?
Use line-height to center it vertically. I usually use the same value as its height. Works only when you know the height. I set height to 0 and line-height to zero and this worked!
We can center the button by using the following methods: text-align: center - By setting the value of text-align property of parent div tag to the center. margin: auto - By setting the value of margin property to auto.
1 Answer. Show activity on this post. A button is an inline element by default, so you can center it by adding a container div around the button and give that container a text-align: center property to align the button correctly. The margin: 0 auto only works when your element is a block-level element.
The exact solution depends on what content exactly is placed into the button, but the general idea is: Use a <button> element. Place a block element inside (a <div> will do fine) Give the block element bottom padding and put your text inside it.
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>
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