线性布局:
线性布局每行每列只能放一个控件;
以下只以分配屏幕宽度Width为例,Height同理可得;
weight默认值是0;
建议:只有将控件宽度设置为0,才是完美的按比例分配;
总结:不管是控件宽度是多少,如果有内容大小屏幕就优先将空间分配给内容大小,然后再将剩余的空间按比例分配给各个控件;
eg.当控件宽度 = 0,控件个数 = n.(黄色):
match_parent - 0*n = 剩余空间
剩余空间按比例分配,分配结果 + 0
eg.当控件宽度 = wrap_content,控件个数 = n.(红色):
match_parent - wrap_content*n = 剩余空间
剩余空间按比例分配,分配结果 + wrap_content
eg.当控件宽度 = match_parent,控件个数 = n.(蓝色):
match_parent - match_parent*n = 剩余空间(此时这个值为负值)
剩余空间按比例分配,分配结果 + match_parent
eg.当控件宽度 = m,控件个数 = n.(紫色):
match_parent - m*n = 剩余空间
剩余空间按比例分配,分配结果 + m
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/linearLayout"
android:background="#dfad4f">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/button"
android:layout_weight="1"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/button2"
android:layout_weight="2"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_below="@+id/linearLayout"
android:layout_alignParentStart="true"
android:id="@+id/linearLayout2"
android:background="#c22222">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/button3"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/button4"
android:layout_weight="2"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_below="@+id/linearLayout2"
android:layout_alignParentStart="true"
android:id="@+id/linearLayout3"
android:background="#28c5da">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/button5"
android:layout_weight="1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/button6"
android:layout_weight="2"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_below="@+id/linearLayout3"
android:layout_alignParentStart="true"
android:id="@+id/linear_layout"
android:background="#bd1db0">
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/button7"
android:layout_weight="1"/>
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/button8"
android:layout_weight="2"/>
</LinearLayout>