I’m having some trouble getting my button text to align correctly in my Android application. Currently, my button text is aligning with the left of the text on the center of the button, as shown:
|Whitespace|Text Here|
I have tried using gravity =”center_horizontal|center_vertical” to no avail. I have tried adding a new button to a completely separate project and this still holds. Also it does this in LinearLayouts and RelativeLayouts.
Thanks in advance for your help.
Here is one of the layout files. However it is doing it in all of them including in other projects. Also, all 3 of the buttons on this layout have the same issue.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:text="@string/history_delete_record"
android:id="@+id/History_Delete_Record"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|center_vertical"></Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/History_Delete_Record"
android:layout_alignLeft="@+id/History_Delete_Record"
android:id="@+id/History_Open_Details"
android:text="@string/history_open_record"></Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/History_Cancel"
android:text="@string/cancel"
android:layout_below="@+id/History_Open_Details"
android:layout_alignLeft="@+id/History_Open_Details"
android:layout_marginTop="19dp">
</Button>
</RelativeLayout>
Here is a simple implementation of a button with centered text:
The problem with your code is that you are setting the width in pixels, when you should be using the xml attribute
android:layout_width="wrap_content", which will wrap the button text to fit the view accordingly.Also note that you should never set a view’s width in pixels as this will not work well across different screen sizes and densities. Instead of using “px”, specify the width in “dp”, a density-independent unit of value. For more information on this topic, see this post.
EDIT
Here is my suggested xml code that you use for your layout: