Align text in center after changing text size and typeface

121 views Asked by At

I have a button and the text is perfectly in the center, but after changing the typeface and size the text is no longer centered but more in the right bottom:

<Button
                    android:id="@+id/button1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginBottom="0dp"
                    android:layout_marginLeft="1dp"
                    android:layout_marginRight="1dp"
                    android:layout_marginTop="1dp"
                    android:layout_weight="1"
                    android:background="@drawable/xbtn_bg"
                    android:text="TestButton"
                    android:textColor="@color/white" />

In the activity:

Button1.setTypeface(CustomTypeFace);
Button1.setTextSize(40);

How can I have either the button re-adjust or move the text to the center?

2

There are 2 answers

0
Vigen On

You can try

button.Gravity = GravityFlags.Center;

see Setting button alignment programmatically

1
Mohammad Rahchamani On

try this :

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.gravity = Gravity.CENTER;

button.setLayoutParams(params);