Chi Chi - 1 month ago 15
Android Question

LinearLayout with percent empty space

I am working on linear layout for my simple android application. I wanna make the portion of two views dynamically change based on the size ( I want to have, for a row for left to right, the first 20% is empty, and all the content is inside the rest of 80%) . For this approach, i chosen the weight for different view. I created an nested linear layout for this approach. For example, the layout hierarchy is something like this.

<linearLayout> //parent layout
<linearLayout //child 1 layout
android:layout_weight="1">
//so that this view occupy 20% of the space regardless the width of device. I intensionally wanna keep this view empty.
</linearLayout>
<linearLayout //child 2 layout
android:layout_weight="4">
//so that this view occupy 80% of the space regardless the width of device. and
//inside this view I have whatever view I wanna add on it.
<EditText>
<ImageView>
</linearLayout>
</linearLayout>


With this approach, the Lint in Android Studio tell me the following warnings:


  1. This is a Nested Layout. Layout weights require a widget to be measured twice. When a LinearLayout with non-zero weights is nested inside another LinearLayout with non-zero weights, then the number of measurements increase exponentially.

  2. the child 1 layout is useless: This
    LinearLayout
    view is useless (no children, no
    background
    , no
    id
    , no
    style
    )



Can anyone address me the right layout to use in order to have the layout dynamically change based on the size of devices? How should I correctly set up the empty space for a linear layout case?

Answer

This is a possible solution using weights:

<LinearLayout
    android:layout_width="match_parent"
    android:gravity="end"
    android:weightSum="1">

    <!-- Your content here: -->
    <View
        android:layout_width="0dp"
        android:layout_weight="0.8"
        android:layout_gravity="end" />

</LinearLayout>