Mark Mark - 1 month ago 15
Android Question

Android percentage width layout

I need to set the width of my view as 50% of the width of the screen and then center this view horizontally while potentially having 1 or more buttons which can appear attached to the left or the right side of the screen.

I'm using a relative layout so that I can place a linear layout with weights to get my 50% centered while placing any buttons on top of that LL attached to the left or right edge of the RL. However this layout is missing the blue middle bar. If I set the middle view layout_weight to 1 I get 3 equal sized bars.

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp">

<LinearLayout
android:id="@+id/stupid_android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<View
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:layout_weight="1" />

<View
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#0000FF"
android:layout_weight="2" />

<View
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1" />

</LinearLayout>

</RelativeLayout>

Answer

You should set view's width to 0dip

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="48dp">

    <LinearLayout
        android:id="@+id/stupid_android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <View
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:background="#FF0000"
            android:layout_weight="1" />

        <View
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:background="#0000FF"
            android:layout_weight="2" />

        <View
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:background="#00FF00"
            android:layout_weight="1" />

    </LinearLayout>

</RelativeLayout>