Relative Layout
RelativeLayout是一个视图组,用于显示相对位置的子视图。每个视图的位置可以指定为相对于同级元素(例如,在另一个视图的左侧或下方)或相对于父级RelativeLayout区域的位置(例如与底部,左侧或中间对齐)。
RelativeLayout是一个非常强大的实用程序,用于设计用户界面,因为它可以消除嵌套视图组并保持布局层次结构平整,从而提高性能。如果您发现自己使用了多个嵌套的LinearLayout组,则可以使用单个RelativeLayout替换它们。
定位视图
RelativeLayout允许子视图指定它们相对于父视图或彼此的位置(由ID指定)。因此,您可以通过右边框对齐两个元素,或者使另一个元素在另一个下方对齐,在屏幕中居中,向左居中,依此类推。默认情况下,所有子视图都在布局的左上角绘制,因此您必须使用RelativeLayout.LayoutParams中提供的各种布局属性来定义每个视图的位置。
RelativeLayout中可用于视图的一些布局属性包括:
如果为“true”,则使此视图的上边缘与父级的上边缘匹配。
如果为“true”,则将此子项垂直居中于其父级。
将此视图的上边缘定位在使用资源ID指定的视图下方。
将此视图的左边缘定位到使用资源ID指定的视图的右侧。
这只是几个例子。所有布局属性都记录在RelativeLayout.LayoutParams中。
每个布局属性的值是一个布尔值,用于启用相对于父RelativeLayout的布局位置,或者一个ID,用于引用布局中应该放置视图的另一个视图。
在XML布局中,可以按任何顺序声明布局中与其他视图的依赖关系。例如,即使“view2”是层次结构中声明的最后一个视图,也可以声明“view1”位于“view2”下面。下面的示例演示了这种情况。
示例
强调控制每个视图的相对位置的每个属性。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<Spinner
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
<Spinner
android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_alignParentRight="true" />
<Button
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/times"
android:layout_alignParentRight="true"
android:text="@string/done" />
</RelativeLayout>
有关RelativeLayout的每个子视图可用的所有布局属性的详细信息,请参阅RelativeLayout.LayoutParams。