Search code examples
androidandroid-linearlayoutcenter

TextView Alignment in LinearLayout android. Unable to place it at Center of Layout


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Team A"
        android:textSize="25sp" />

    <!-- unable to place this 3 TextViews at center position of layout -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <!-- make this as center -->

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="00"
            android:textSize="70sp" />

        <!-- make this as center -->

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="/"
            android:textSize="70sp" />

        <!-- make this as center -->

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"
            android:textSize="70sp" />
    </LinearLayout>

Solution

  • Add android:gravity="" attribute to the parent LinearLayout of those 3 TextViews with value of center_horizontal. Those TextViews will be centered.

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_horizontal" >
    
       <TextView ... />
    
       <TextView ... />
    
        <TextView ... />
    
    </LinearLayout>