Xamarin.Android RelativeLayout

RelativeLayout 是一个 ViewGroup,它在相对位置 显示子级 View 元素。 可以将 View 的位置指定为相对于同级元素(例如在给定元素左侧或下方),或者相对于 RelativeLayout 的区域的位置(例如与底部对齐,居中左对齐)。

RelativeLayout 对于设计用户界面来说是一个非常强大的工具,因为它可以消除嵌套的 ViewGroup。 如果你发现自己使用多个 嵌套的 LinearLayout 组,你也许能够将它们替换为单个 RelativeLayout

启动一个名为 HelloRelativeLayout 的新项目。

打开 Resources/Layout/Main.axml 文件并插入以下内容:

<?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">
    <TextView
        android:id="@+id/label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Type here:"/>
    <EditText
        android:id="@+id/entry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_below="@id/label"/>
    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/entry"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dip"
        android:text="OK" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/ok"
        android:layout_alignTop="@id/ok"
        android:text="Cancel" />
</RelativeLayout>

请注意每个 android:layout_* 特性,例如 layout_belowlayout_alignParentRightlayout_toLeftOf。 使用 RelativeLayout 时,可使用这些特性来描述要如何定位每个 View。 其中每个特性都定义了一种不同类型的相对位置。 某些特性使用同级 View 的资源 ID 来定义自己的相对位置。 例如,根据定义,最后一个 Button 在 ID ok 标识的 View(即,之前的 Button)左侧且与其顶部对齐。

所有可用的布局特性都在 RelativeLayout.LayoutParams 中定义。

确保将此布局加载到 OnCreate() 方法插入以下代码:

protected override void OnCreate (Bundle savedInstanceState)
{
    base.OnCreate (savedInstanceState);
    SetContentView (Resource.Layout.Main);
}

SetContentView(int) 会为 Activity 加载布局文件,该文件由资源 ID 指定 - Resource.Layout.Main 是指 Resources/Layout/Main.axml 布局文件。

运行该应用程序。 应该会看到以下部署:

Screenshot of a relative layout with a TextView, EditText, and two buttons

资源

本页的部分内容是根据 Android 开放源代码项目创建和共享的工作进行的修改,并根据知识共享署名 2.5 通用许可协议中的条款进行使用。