Sheehan Alam
Sheehan Alam

Reputation: 60919

How to tell layout to space everything 50/50?

I have a vertical linear layout with two ListViews. I want the top ListView to take up 50% of the screen. I want the bottom listivew to take up 50% of the screen. How can I do this in XML?

Upvotes: 2

Views: 4722

Answers (2)

Priyank
Priyank

Reputation: 10623

Set Vertical LinearLayout to have height:fill_parent and then set the weight of each ListView to "1" e.g. android:layout_weight="1"

Upvotes: 2

Joseph Earl
Joseph Earl

Reputation: 23432

The following layout should work

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >

    <ListView
        android:id="@+id/list1"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />

    <ListView
        android:id="@+id/list2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />

</LinearLayout>

How this works:

  • Initially both lists have no height
  • After measuring everything with a height, the remaining height (in this case all of it as there are no other views with a specified height or wrap_content) is divided up between all the views with no height and a layout_weight
  • The height of each view will be (layout_weight of View) / (Sum of layout_weights in parent ViewGroup)
  • In this case, (Sum of layout_weights in parent ViewGroup) = 2 and (layout_weight of View) = 1 for each ListView, so each ListView occupies 1/2 of the available space

Upvotes: 13

Related Questions