My question is very simple.
How do I center the text on a button in android?
I tried to set padding to 0, gravity to center but the result when i run it still that the text is horizontal centred but not vertical. The text is a bit shifted to the bottom.
<Button
android:id="@+id/btnSame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:background="@drawable/layout_button_different"
android:gravity="center_vertical|center_horizontal"
android:height="30dp"
android:padding="0dip"
android:text="@string/equals"
android:textColor="@drawable/layout_button_different"
android:textSize="50dp"
android:width="70dp" />
My be also relevant:
In activity I do this:
btnEquals.setCompoundDrawablesWithIntrinsicBounds(null,getResources().getDrawable(R.drawable.up2), null, null);
btnEquals.setPadding(0, 5, 0, 0);
btnEquals.setTextSize(15);
This works but after this I set this:
btnEquals.setCompoundDrawables(null, null, null, null);
btnEquals.setPadding(0, 0, 0, 0);
Result is a bad vertical alignment.
Your existing layout cannot hope to center the text due to the sizes you have selected. You've set the button height to 30dp
and your textSize is 50dp
, and for whatever reason, Android is unable to deal with that and center the text. If you make your button larger or your text smaller you'll see that the centering works.
It's very easy, you can put this:
android:textAlignment="center"
There are three systems to consider. The xml layout designer, the simulator, and real phone. The text in the button if you specify gravity="center" will look like this.
In xml layout designer it will look like the leftmost letter is in the center of the button but the rest of the letters are to the right. (looks incorrect)
In simulator, the text shows well in the center. (correct)
In phone, the text shows well in the center. (correct)
You can also use negative numbers in setPadding. This may help if your font is large and your button is small. Try also setting the top or bottom to a more negative number if it's still off center.
You can just add this line to your Button in layout xml code:
android:gravity="center"
<Button
android:id="@+id/AnswerE"
style="@style/defaultbuttonstyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:onClick="AnswerCheck"
android:text=" E "
android:textStyle="bold" />
This worked for me