Layout_weight属性的使用与理解

来源:互联网 发布:逆战刷枪软件2017 编辑:程序博客网 时间:2024/05/18 02:51

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

<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的定义:

 @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”:

    <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的描述找到没有权威的解,所以在后续的学习中还会就这一问题作出解释。

1 0
原创粉丝点击