手机屏幕的划分
在实际应用中,大家经常会遇到分割屏幕的需求,例如两个控件的宽度比为1:3,或者某个控件的宽度占总屏幕的1/3等。本例子将实现屏幕垂直分割成上、中、下3个效果,它们的高度比例为1:4:1,然后将中间部分又划分为左、中、右3个部分,它们的高度比为1:4:1。
举例说明:例如有3个控件水平排列,他们的宽度都为wrap_content时,整个屏幕宽度为X,他们的layout_weight属性值分别为1、2、3,则表示第一个控件除了自己的宽度以外还额外占剩余空间宽度的1/6(6=1+2+3)。以此类推,第二个控件还额外占剩余空间宽度的1/3,第三个控件还额外占剩余宽度的1/2。
计算公式: 剩余空间的宽度=X-a控件的宽度-b控件的宽度-c控件的宽度
3个控件的宽度之比为:(a控件的宽度+1/6 X 剩余空间的宽度):(b控件的宽度+1/3 X 剩余空间的宽度):(c控件的宽度+1/2 X 剩余空间的宽度),由于a、b、c控件自身的宽度关系并不确定,因此他们之间的宽度之比没有关系。若想达到分割的目的,有两种方案:一设置所有控件的宽度为0,二是设置所有控件的宽度为match_parent。
当设置所有控件的宽度为时,此时剩余空间就是X-0-0-0=X,这样它们的宽度比就是(0+1/6 X):(0+1/3 X ):(0+1/2 X)=1:2:3。
当设置所有控件的宽度为match_parent时,此时剩余空间就是X-X-X-X=-2X,这样它们的宽度比就是(X+1/6 X (-2X)):(X+1/3 X (-2X)):(X+1/2 X (-2X))=2:1:0,即c控件无法显示。
本例中使用两次,实现屏幕垂直分割成上、中、下3个效果,它们的高度比例为1:4:1,(设置高度为0,layout_weight属性值分别为1,4,1);然后将中间部分又划分为左、中、右3个部分,它们的高度比为1:4:1(设置高度为0,layout_weight属性值分别为1,4,1)。-
代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#aabbcc" android:orientation="vertical" tools:context="${relativePackage}.${activityClass}" > <Button android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="4" android:text="@string/up" /> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="4" android:orientation="horizontal" > <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="@string/left" /> <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="4" android:text="@string/center" /> <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="@string/right" /> </LinearLayout> <Button android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:text="@string/down" /> </LinearLayout>
-
效果
<span style="font-size:14px;"></span>
<span style="font-size:14px;"></span>