Using a RelativeLayout to vertically split two fragments evenly

五迷三道 提交于 2019-12-06 04:18:01

Here is my solution with a common workaround to avoid nested weight :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_marginLeft="0dp"
              android:layout_marginRight="0dp"
              android:baselineAligned="false"
              android:divider="?android:attr/dividerHorizontal"
              android:orientation="horizontal"
              android:showDividers="middle"
              tools:context=".MainActivity" >
    <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_weight="1" >

        <View android:id="@+id/dummyView"
              android:layout_width="0dp"
              android:layout_height="0dp"
              android:layout_centerInParent="true"/>
        <fragment
                android:id="@+id/fragment1"
                android:name="com.example.Fragment1"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_alignTop="@id/dummyView"
                tools:layout="@android:layout/list_content" />

        <fragment
                android:id="@+id/fragment2"
                android:name="com.example.Fragment2"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_alignBottom="@id/dummyView"
                tools:layout="@android:layout/list_content" />

    </RelativeLayout>

    <FrameLayout
            android:id="@+id/action_detail_container"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3" />

</LinearLayout>

Why not switch it around, i.e. use a RelativeLayout as your root view, and a vertical LinearLayout as a container for the fragments? Just use alignParentLeft on the container and toRightOf on the FrameLayout.

Jave

Using weights are usually just bad for performance when they are nested (See this for example). So in your case you could use them.
Otherwise, you can create an empty view in the middle to help you position the others:

<RelativeLayout
    ...
    >
    <View
    androi:id="@+id/separator"
    android:layout_centerVertical="true"
    android:layout_width="0"
    android:layout_height="0"
    >
    <fragment
    android:layout_above="@id/separator"
    ...
    >
    <fragment
    android:layout_below="@id/separator"
    ...
    >
</RelativeLayout>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!