Android Layouts: How to avoid nested weights?

Frank picture Frank · Jan 28, 2013 · Viewed 10.2k times · Source

guys. I'm trying to code a layout for an activity which contains 4 different fragments, a list fragment and three detail-related fragments. I try to make it look like the following diagram enter image description here

With LinearLayout I can get the 30/70 ratio between the list fragment and the detail area (where the other three fragments are supposed to be). However, when dealing with these three fragments I really don't know how to keep them within the ratios I expect them to have, since you cannot nest layouts with weightSum attributes.

I've been trying with RelativeLayouts but don't want to go with 'wrap_content' values, since some of the contents be bigger than others, breaking thus the appearance I'm trying to achieve.

Is there a way to do this? I know of the TableLayouts, but AFAIK they're like HTML tables: something to use with data, not as a lay out tool...

Answer

luixal picture luixal · Jan 28, 2013

Nested weights should work just fine, I've used them a few times although eclipse shows a hint telling that "nested weights are bad for performance".

You should try something like:

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

    <LinearLayout android:id="@+id/layout_fragment_a"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="0.5"/>

    <LinearLayout android:id="@+id/layout_container_b_c"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="0.5"
        android:weightSum="1"
        android:orientation="vertical">

        <LinearLayout android:id="@+id/layout_fragment_b"
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="0.7"/>

        <LinearLayout android:id="@+id/layout_fragment_c"
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="0.3"/>

    </LinearLayout>

</LinearLayout>

And that's the way I've done it other times. The xml can have some failures and typos (writting rigth now here in the response box :P) but it should help you getting the idea: one main layout (main_layout) using full space and containing two second level layouts 50% width each one (fragment_a and container_b_C) and another tow layouts in onw of the second level layouts splitting the space in that layout 70/30 (fragment_b and fragment_c) :)

Hope it helps!