Reputation: 643
I have a fragment which fill all of the screen. Now, If i add a new fragment i would like that each fragment fill half of the screen. How can I do this?
I tried this layout and programmatically added fragments. But it doesn't work.
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="tech.test.org.game.Game$PlaceholderFragment">
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="50">
</RelativeLayout>
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_below="@+id/relativeLayout"
android:layout_weight="50"
>
</RelativeLayout>
</RelativeLayout>
Thanks.
Upvotes: 2
Views: 4588
Reputation: 516
The answer given by Kat-hat is also correct but it takes to much load, to load the UI which may hamper the performance.
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
>
</RelativeLayout>
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:visibility="gone" >
</RelativeLayout>
</LinearLayout>
when you are adding second fragment do programatically set layout2 visibility to visible.
findViewById(R.id.relativeLayout2).setVisibility(View.VISIBLE);
Upvotes: 3
Reputation: 1444
Use Linear layout instead of Relative layout and set layout as
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="100" >
<LinearLayout
android:id="@+id/layout1"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="100" >
<fragment
android:id="@+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</fragment>
</LinearLayout>
<LinearLayout
android:id="@+id/layout2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:visibility="gone" >
<fragment
android:id="@+id/fragment2"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</fragment>
</LinearLayout>
</LinearLayout>
And when you are adding second fragment do programatically set layout2 visibility to visible and layout1 weight to 50
LinearLayout layout1 = (LinearLayout) findViewById(R.id.layout1);
android.widget.LinearLayout.LayoutParams par = layout1.getLayoutParam();
par.weight =50;
Upvotes: 2