Search code examples
androidapitextviewgravity

TextView gravity not working on API 18 or higher


I have an TextView wich overlaps some other view. Everything works great, except the gravity on API equal or higher than 18.

Here is my TextView:

<TextView
    android:id="@+id/overlappingTextView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignBottom="@id/behindLinearLayout"
    android:layout_alignLeft="@id/behindLinearLayout"
    android:layout_alignRight="@id/behindLinearLayout"
    android:layout_alignTop="@id/behindLinearLayout"
    android:background="@drawable/overlapping_bg"
    android:gravity="center"
    android:text="Waiting for user confirmation..."
    android:textColor="@color/blue" />

The gravity works ok on 4.2.2 or lower but is not working on 4.3 and higher ... It works only partially, it is centered but only vertically.

On API 4.1.2 On API 4.3 LE:

There is no fix for this issue? Or does anyone know why this is happening?


Solution

  • This appears to be a known issue in API 18+, and there's a workaround involving wrapping your view in a LinearLayout.

    See the answer in this thread.

    In your case, the fixed code should look something like:

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_alignBottom="@id/behindLinearLayout"
        android:layout_alignLeft="@id/behindLinearLayout"
        android:layout_alignRight="@id/behindLinearLayout"
        android:layout_alignTop="@id/behindLinearLayout"
        android:background="@drawable/overlapping_bg" >
    
        <TextView
            android:id="@+id/overlappingTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="Waiting for user confirmation..."
            android:textColor="@color/blue" />
    
    </LinearLayout>