views:

32

answers:

1

Why doesn't the following code align with the center? What do I have to do to fix it?

<AbsoluteLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_gravity="center" 
    android:id="@+id/parent" 
    android:layout_height="match_parent" 
    android:layout_width="match_parent" 
    android:background="@color/blue">

<RelativeLayout
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_width="wrap_content">


    <Button 
        android:layout_gravity="center" 
        android:id="@+id/Question01" 
        android:text="12 + 23" 
        android:gravity="center_vertical|center_horizontal"
        android:layout_height="70px" 
        android:lines="1" 
        android:textSize="40px" 
        android:layout_alignWithParentIfMissing="true" android:background="@drawable/orange_button" android:layout_margin="5px" android:layout_width="230px" android:textColor="@color/blue"/>


</RelativeLayout>
</AbsoluteLayout>
+1  A: 

Well, android:layout_gravity is not about positioning of child views, it's about positioning of current view within its parent. Try using android:gravity for AbsoluteLayout (also you may want to switch to FrameLayout instead of Abdolute). For RelativeLayout, use android:layout_centerInParent="true" on the button.

<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center" 
android:id="@+id/parent" 
android:layout_height="match_parent" 
android:layout_width="match_parent" 
android:background="@color/blue">
<RelativeLayout
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content">
<Button 
    android:layout_gravity="center" 
    android:id="@+id/Question01" 
    android:text="12 + 23" 
    android:gravity="center_vertical|center_horizontal"
    android:layout_height="70px" 
    android:lines="1" 
    android:textSize="40px" 
    android:layout_alignWithParentIfMissing="true"
    android:background="@drawable/orange_button" 
    android:layout_margin="5px" android:layout_width="230px" 
    android:textColor="@color/blue"
    android:layout_centerInParent="true"/>
</RelativeLayout>
</AbsoluteLayout>
Konstantin Burov
+1 for not using `AbsoluteLayout`
Christopher