problems with text alignment

Viewed 53

i have a problem with the output of my code, when I use android:gravity="center_horizontal" the text is not aligned as indicated

This is the code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/name_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/press"
        android:textColor="@color/purple_200"
        android:textSize="30sp" />
</Linear Layout>

the result photo:
the result photo

code photo:
code photo

1 Answers
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/name_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/press"
        android:textColor="@color/purple_200"
        android:textSize="30sp" />
</LinearLayout> 
  1. Your ending bracket had an unnecessary space </Linear Layout>
  2. Use layout_gravity instead of gravity:

Layout Gravity affects your position in the superview. Gravity affects the position of your subviews within you.

Related