同时设置layout_width与layout_weight:,layout_width为0dp时 layout_weight生效 当layout_width不为0时 优先生效 其次layout_weight
1, 当layout_width为0dp时
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_height="0dp"
>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#98FB98"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#FFFF00"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="match_parent"
android:background="#FF00FF"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#fff"
>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_height="0dp"
>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#98FB98"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#FFFF00"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="match_parent"
android:background="#FF00FF"
/>
</LinearLayout>
</LinearLayout>
2;将左上的textview 的layout_width="wrag_content" 与上图一样 但是 向里面添加text""就会不一样了:
<TextView
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="#98FB98"
android:text="aaaaaaaaaaaaaaaaaaaaaa"
/>
wrap_content先起作用根据内容占据相应的空间 最后再按照weight分
3.将 layout_width设置成match_parent 会发现第三个textview不见了
屏幕只有一个宽设为x 但是a,b,c都想占满 . a直接占住屏幕 b,c在占时屏幕没了 这个时候缺少2个屏幕了 也就是-2 每个view权重仍然会去分
a的实际宽度应该为 width+剩下屏幕*(weightA)/(weightA+weightB+weightC) 也就是 x+(-2x)*(weightA)/(weightA+weightB+weightC) 3/5x
b同理x+(-2x)*(weightA)/(weightA+weightB+weightC) 3/5x 此时 a ,b合起来一起超过x了 所以b为2/5x c无立足之地 就这样消失了..
总结: 每个组件的layout_width属性先占去一部分 剩下的weight分
每个组件的实际宽度为 layout_width +剩下的根据weight分来的(剩下的指的是 屏幕的总宽-每个组件的width)
设 总宽 为 x 有三个组件每个的 width为 xa xb xc weight为 wa wb wc
a的实际宽 xa+(x-xa-xb-xc)*(wa/(wa+wb+wc))
b c也是一样的计算方法