资讯是做网站还是公众号,上饶网站开发 app开发,济南网站优化推广,网站名称格式在日常的开发过程中#xff0c;我们通常或多或少会使用到LinearLayout的weight属性来进行权重设置#xff0c;进而达到按比例显示布局的意图通常我们在使用时#xff0c;会这样使用android:layout_widthmatch_parentandroid:layout_heightmatch_parent我们通常或多或少会使用到LinearLayout的weight属性来进行权重设置进而达到按比例显示布局的意图通常我们在使用时会这样使用android:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:orientationhorizontalandroid:layout_width0dpandroid:layout_heightmatch_parentandroid:layout_weight2android:backgroundandroid:color/holo_blue_light /android:layout_width0dpandroid:layout_heightmatch_parentandroid:layout_weight1android:backgroundandroid:color/holo_red_light /android:layout_width0dpandroid:layout_heightmatch_parentandroid:layout_weight1android:backgroundandroid:color/holo_green_light /权重示例.png我们一般使用weight属性时会将width或者height设置为0dp这时控件的宽或者高就会按照我们设置的权重如上面的2:1:1来填充父控件但是如果子控件的宽度或高度不设置成0dp那么他们的宽高是怎么分配的呢我们首先明确一点weight权重是针对于LinearLayout的剩余空间所以我们在设置该属性之后LinearLayout会计算自己的剩余空间然后将剩余空间按权重分配到子控件上。以横向布局为例LinearLayout的剩余空间 LinearLayout的宽度 - 各个子控件的宽度可以有负值以2个子控件为例权重分别为2和1那么子控件1的宽度 子控件1的初始宽度 (2/3)* LinearLayout的剩余空间子控件2的宽度 子控件2的初始宽度 (1/3)* LinearLayout的剩余空间我们来验证一下为方便测量使用px单位 我们先设定父控件宽 800px 子控件1 200px 子控件2 100pxweight都为1我们自己先算一下可以得出LinearLayout的剩余空间 800 - 200 - 100 500子控件1宽度 200 (1/2) * 500 450子控件2宽度 100 (1/2) * 500 350看下效果是否和我们计算的一致android:layout_width800pxandroid:layout_heightmatch_parentandroid:orientationhorizontalandroid:layout_width300pxandroid:layout_heightmatch_parentandroid:layout_weight1android:backgroundandroid:color/holo_blue_light /android:layout_width100pxandroid:layout_heightmatch_parentandroid:layout_weight1android:backgroundandroid:color/holo_red_lightandroid:singleLinetrue /权重示例1.png和我们预期的一致我们再检测下match_parent的情况设定父控件宽 600px 子控件1 match_parent weight 1 子控件2 match_parent weight 2我们自己先算一下可以得出LinearLayout的剩余空间 600- 600- 600 -600子控件1宽度 600 (1 / 3) * (-600) 400子控件2宽度 600 (2 / 3) * (-600) 200看下效果是否和我们计算的一致android:layout_width600pxandroid:layout_heightmatch_parentandroid:orientationhorizontalandroid:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:layout_weight1android:backgroundandroid:color/holo_blue_light /android:layout_widthmatch_parentandroid:layout_heightmatch_parentandroid:layout_weight2android:backgroundandroid:color/holo_red_lightandroid:singleLinetrue /权重示例2.png和我们计算的完全一致子控件wrap_content与确定值计算方式同上有空的可以验证下另外需要注意一点weight是float类型