为什么 android:layout_width=”0px”对于碎片?
在片段示例中,布局宽度始终为零。这个价值的背后是什么?
The layout width is always zero in fragment examples. What is behind this value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了更好地解释,请查看开发指南中片段的设计哲学。
如果您查看该图像,左侧会显示手机如何显示初始活动 A,然后在选择列表中的项目时启动活动 B。
然而,右侧显示了如何将这两个活动同时显示为片段。请注意,片段 A 占据了屏幕的 1/3,片段 B 占据了屏幕的 2/3。
现在查看该布局的 XML,来自同一个将片段添加到活动开发指南文章...
您可以看到两个 Fragment 的
layout_width
均为 0dp,但它们也各自具有layout_weight
属性。第一个的权重为 1,第二个的权重为 2。简而言之,当使用这样的布局时,将“宽度”设置为 0 意味着您不想显式强制宽度并且操作系统应该可以工作将相对宽度表示为总重量的分数。换句话说,1+2=3(总重量),但第一个 Activity 想要的宽度为 1 / 总重量 = 屏幕宽度的 1/3,而 Fragment B 想要的宽度为 2 / 总宽度 = 屏幕宽度的 2/3。
现在假设您添加第三个片段,其宽度也=0dp,重量=2。在这种情况下,总权重为 1+2+2=5,第一个片段的相对宽度为 1/5,其他两个片段的相对宽度为屏幕的 2/5 或 20%/40%/40%。
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...
You can see that both Fragments have a
layout_width
of 0dp but they also each have alayout_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%.
这对我有用:
对布局中的所有权重求和。在 Squonk 发布的示例中,有 2 个片段,总权重为 3。
片段 ArticleListFragment 的权重=1,这意味着
大小将为屏幕的 1/3(3 是总重量)。
片段 ArticleReaderFragment 的权重 =2,这意味着大小将为屏幕的 2/3。
希望有帮助。
This has worked for me:
Sum all weights in the layout. In the example that Squonk posted, there are 2 fragments and total weight is 3.
The fragment ArticleListFragment has a weight=1, meaning that the
size will be 1/3 ( 3 is the total weight) of the screen.
The fragment ArticleReaderFragment has a weight =2, meaning that the size will be 2/3 of the screem.
Hope it helps.