Mayank Wadhwa Mayank Wadhwa - 4 months ago 17
Android Question

Cannot add weight param to fragment in android studio?

I am trying to add weight param to fragment xml in android studio so that my two fragements can take half screen each but adding weight have no effect on the layout. what interesting is i still can add weight to normal activity views here is the screen shot

Here is my layout file

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="io.designcoder.vivz.lifecycle.xml.ActivityFragmentXml">

<fragment
android:id="@+id/fragment_xml_a"
class="io.designcoder.vivz.lifecycle.xml.FragmentXmlA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:layout="@layout/fragment_xml_a"
/>
<fragment
android:id="@+id/fragment_xml_b"
class="io.designcoder.vivz.lifecycle.xml.FragmentXmlB"
android:layout_width="match_parent"
android:layout_below="@id/fragment_xml_a"
android:layout_height="wrap_content"
tools:layout="@layout/fragment_xml_b"
/>

</RelativeLayout>

Answer

You should not use Relative layout as weight would not work there. So User Linear layout for that.

<?xml version="1.0" encoding="utf-8"?>
<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:weightSum="2"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="io.designcoder.vivz.lifecycle.xml.ActivityFragmentXml">

<fragment
    android:id="@+id/fragment_xml_a"
    class="io.designcoder.vivz.lifecycle.xml.FragmentXmlA"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    tools:layout="@layout/fragment_xml_a"
    />
<fragment
    android:id="@+id/fragment_xml_b"
    class="io.designcoder.vivz.lifecycle.xml.FragmentXmlB"
    android:layout_width="match_parent"
    android:layout_below="@id/fragment_xml_a"
    android:layout_height="0dp"
    tools:layout="@layout/fragment_xml_b"
    />

</LinearLayout>