Home » Android » Why android:layout_width=”0px” for fragments?

Why android:layout_width=”0px” for fragments?

Posted by: admin June 15, 2020 Leave a comment

Questions:

The layout width is always zero in fragment examples. What is behind this value?

How to&Answers:

To hopefully explain, take a look at the Design Philosophy for Fragments in the Dev Guide.

If you look at the image, to the left it shows how a phone would show an intial Activity A which would then start Activity B when an item in a list is selected.

To the right, however, it is showing how those two Activities can be shown as Fragments at the same time. Notice Fragment A is taking 1/3 of the screen and Fragment B is filling 2/3 of the screen.

Now look at the XML for that layout from Adding a fragment to an activity from the same Dev Guide article…

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
    <fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

You can see that both Fragments have a layout_width of 0dp but they also each have a layout_weight attribute. The first has a weight of 1 and the second a weight of 2.

In short, when using a layout like this, setting the ‘width’ to be 0 means you don’t want to explicitly enforce a width and that the OS should work out the relative widths as fractions of total weight. In other words 1+2=3 (total weight) but the first Activity wants a width of 1 / total weight = 1/3 of the screen width and Fragment B wants 2 / total width = 2/3 of the screen width.

Now suppose you add a third fragment which also has width=0dp and weight=2. In this case, the total weight is 1+2+2=5 and the first fragment will have a relative width of 1/5 and the other two fragments 2/5 of the screen or 20% / 40% / 40%.

Answer:

This has worked for me:

  1. Sum all weights in the layout. In the example that Squonk posted, there are 2 fragments and total weight is 3.

  2. The fragment ArticleListFragment has a weight=1, meaning that the
    size will be 1/3 ( 3 is the total weight) of the screen.

  3. The fragment ArticleReaderFragment has a weight =2, meaning that the size will be 2/3 of the screem.

Hope it helps.