最近仿照书上的例子,看到layout_weight有点不懂,查了很多资料,写写自己的看法(仅对效果做笔记)
布局的时候,系统先按照view的layout_width和layout_height来布局,然后再根据layout_weight对view的位置进行调整。
利用按钮作为例子
先来看下面的例子
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#a473a2"
android:text="1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80d67e"
android:text="2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#c2ad97"
android:text="3" />
</LinearLayout>
呈现的效果是各个按钮根据内容适配大小
===================================
接下来在按钮2改为
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#80d67e"
android:layout_weight="1"
android:text="2" />
变为
可以看出,按钮2中android:layout_weight="1"作用是按钮1和3保持不变的大小,分配屏幕剩下的空间给按钮2。因为他的权重是1,我试着把他设为2、3等数,一样的效果。(我也不知道为啥要设成2、3,只是想看看效果)
===============================
我拿了别的博主的解释:
1、我们只有在button2使用了layout_weight属性,并赋值为1;但是button1和button3并没有使用这个属性,根据API可以知道,他们的layout_weight属性等于0。
2、LinearLayout如果显式包含layout_weight属性时,会measure两次;第一次将正常计算三个button的宽高,第二次将结合layout_weight的值分配剩余的空间。
通俗点来总结:Android系统先按照你设置的3个Button高度Layout_height=wrap_content,给你分配好他们3个的高度,然后会把剩下来的屏幕空间全部赋给Button2,因为只有他的权重值是1,这也是为什么Button2占了那么大的一==
======================
如果layout_width和layout_height都设置为
wrap_content
效果就只是按内容适配大小
如果在按钮2加上android:layout_weight="1",则会根据LinearLayout的
orientation值进行按钮2的“拉伸”
android:orientation="horizontal">
================
android:orientation="vertical">
如果layout_width和layout_height都设置为
match_parent
每个属性都要设置权重才会有意义,就是每个按钮都按一定的比例去占据整个屏幕
=========================
现在才是重点,以vertical为例,重点在layout_height
如果layout_width为match_parent
layout_height为wrap_content时
按钮会按照每个权重的比例进行分配大小,比如按钮1、2、3的权重分别为1:2:2,则按钮1、2、3的height比例也为1:2:2
如果layout_width为wrap_content
layout_height为match_parent时
则会出现反差:权重越大,所占的空间越小
例如:按钮1、2、3的权重分别为1:2:2
大致可以看出是3:1:1
这个怎么来的呢。
有个公式:
每个layout_height为match_parent,所以每个按钮(view)的高度都是 parent-height,总高度为3* parent-height
即单个按钮的高度为parent-height
总高度为3* parent-height
则剩余高度为单个按钮的高度减去总高度
剩余高度=单高度-总高度=parent-height - 3*parent-height=(-2)*parent-height(我也不知道为啥要这样计算)
每个按钮的实际高度=单高度+它所占的权重的比例*剩余高度
例如按钮1的实际高度为=1+1/(1+2+2)*(-2)=3/5 parent-height
按钮2的实际高度为=1+2/(1+2+2)*(-2)=1/5 parent-height
按钮3的实际高度为=1+2/(1+2+2)*(-2)=1/5 parent-height
即3:1:1
以horizontal为例,重点在layout_width,道理是一样的
============
仅仅是个人理解,有错的话希望可以指出来
最后给上参考链接,从这个博主哪里总结来的
https://www.cnblogs.com/net168/p/4227144.html
https://blog.csdn.net/ddiididi/article/details/80954084