我是靠谱客的博主 微笑身影,这篇文章主要介绍Layout_weight属性的使用与理解,现在分享给大家,希望可以做个参考。

在一个项目中使用了自定义控件,在定义该自定义控件的布局时使用了LinearLayout布局中的Layout_weight属性,仔细了解了一下这个属性,在这里把我知道的写出来,有不对的地方希望大神指正。
Layout_weight属性只适用于LinearLayout的布局中,而在使用时先写了这样的布局:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<LinearLayout android:id="@+id/list_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ListView android:id="@+id/order_list_one" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_weight="1"/> <ListView android:id="@+id/order_list_two" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_weight="4" /> </LinearLayout>

显示出来的布局是这样的:
这里写图片描述
两个list的宽度比却相反,搜索了一下,发现使用Layout_weight属性涉及到了剩余空间的概念,在这里我就不赘述了推荐一篇博客:
※WYF※的博客
但是仔细的同学可能发现了,就是我使用的也是Layout_width=“wrap_content”但是显示的效果还是与我的想法相悖,我又去查了一下wrap_content的定义:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@SuppressWarnings({"UnusedDeclaration"}) @Deprecated public static final int FILL_PARENT = -1; /** * Special value for the height or width requested by a View. * MATCH_PARENT means that the view wants to be as big as its parent, * minus the parent's padding, if any. Introduced in API Level 8. */ public static final int MATCH_PARENT = -1; /** * Special value for the height or width requested by a View. * WRAP_CONTENT means that the view wants to be just large enough to fit * its own internal content, taking its own padding into account. */ public static final int WRAP_CONTENT = -2; /** * Information about how wide the view wants to be. Can be one of the * constants FILL_PARENT (replaced by MATCH_PARENT * in API Level 8) or WRAP_CONTENT, or an exact size. */

发现wrap_content的值为-2,意味着宽度设为wrap_content控件宽度是不为0的,由于没有找到关于-2到底在描画过程中表示什么,只好猜测该值在计算剩余空间的时候最小与fill_parent相同,那么由上文引用的博客中写的计算方法可知为何显示出来的控件宽度与我料想的不同了,而如果我们设置Layout_width=”0dp”:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<LinearLayout android:id="@+id/list_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ListView android:id="@+id/order_list_one" android:layout_height="match_parent" android:layout_width="0dp" android:layout_weight="1"/> <ListView android:id="@+id/order_list_two" android:layout_height="match_parent" android:layout_width="0dp" android:layout_weight="4" /> </LinearLayout>

那么由计算公式剩余空间为:1个parent_width - 2 * 0 = 1个parent_width(这里只屏幕宽度);
第一个list的宽度=0 + 1/5 * (1parent_width) = 1/5parent_width(这里指屏幕宽度);
第二个list的宽度=0 + 4/5 * (1parent_width) = 4/5parent_width(这里指屏幕宽度);
显示出来为下图:
这里写图片描述
这样就符合我们的要求了。
由于对于wrap_content的描述找到没有权威的解,所以在后续的学习中还会就这一问题作出解释。

最后

以上就是微笑身影最近收集整理的关于Layout_weight属性的使用与理解的全部内容,更多相关Layout_weight属性内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部