为什么机器人:layout_width =“0px”​​的片段?机器人、片段、layout_width、px

2023-09-06 02:24:07 作者:我年轻我任性

的布局宽度总是零在片段的例子。这背后有什么价值?

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

推荐答案

要希望解释一下,看看在的设计理念的开发指南中的片段。

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

如果你看一下图片,左侧它表明了一个电话会显示一个intial活动一这将随后启动b活动时,列表中的一个项目被选中。

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.

要的权利,但是,它呈现出这两个活动如何可以表示为片段在同一时间。通知片段A走的是屏幕的1/3和片段B被占满屏幕的2/3。

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.

现在看看XML从的布局添加一个片段活动从相同的开发指南的文章......

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>

您可以看到,这两个片段具有 layout_width 的0dp但他们也都有一个 layout_weight 属性。所述第一权重为1和2的第二重

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.

总之,采用这样的布局时,设置'宽度'为0意味着你不想明确强制执行的宽度和操作系统应该制定出相对宽度为总重量的分数。换句话说1 + 2 = 3(总重量),但在第一活动希望的1 /总重量=屏幕宽度的1/3的宽度和片段B想要2 /总宽度=屏幕宽度的2/3。

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.

现在假设你添加第三个片段,其中也有宽度= 0dp和重量= 2。在这种情况下,总重量是1 + 2 + 2 = 5和第一片段将具有1/5的相对宽度和其他两个片段2/5屏幕或20%/ 40%/ 40%。

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%.