解析:使用FrameLayout 可以很容易解决这个问题,
方法一:View 的上、下、左、右、居中对齐是界面中经常接触到的布局效果。单独某种对齐方式有很多种写法。但同一个方向的各种对齐布局,FrameLayout 是最容易实现的。每个View对一个的xml标签都有一个android:layout_gravity属性,通过设置该属性,可以在FrameLayout 中实现任何方向的对齐布局。由于FrameLayout中的VIew是层叠显示的,因此,可以单独对待FrameLayout 中的每一个View。这一点与LinearLayout差异很大。在LinearLayout中的View并不是对每一个android:layout_gravity 属性的值都起作用。 如android:orientation 属性的值为horizontal ,LInearLayout 中的View都会水平排列,但VIew的android:layout_gravity 属性只有在垂直(如bottom、center_vertical 等)方向的值才起作用。
当然除了FrameLaout还可以使用嵌套LinearLayout,而且,LinearLayout中使用最常见。
方法二:由于水平对齐必须将LinearLayout 标签的android:orientation 属性设置 为 vertical 。因此,可以在一个水平线性布局中放置三个垂直线性布局的LinearLayout,并将android:layout_weight 属性值设置为1,最后将android:layout_width 属性设置为fill——parent 。这样三哥哥垂直线性布局的LInearLayout 就会水平三等分进行排列。然后分别在这3个LinearLayout 设置成不同的背景色,看一下布局后的效果,如果所示。
具体布局如下:
<?xml version="1.0" encoding="utf-8"?> <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:orientation="horizontal" tools:context=".TETActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1" android:background="#f00"> <!-- 左对齐的按钮--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我的按钮1"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1" android:background="#0f0"> <!-- 居中对齐的按钮--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="我的按钮2"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1" android:background="#00f"> <!-- 右对齐的按钮--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="我的按钮3"/> </LinearLayout> </LinearLayout>