0
0

简单Android相对布局实例

2011/05/20 · 评论 
RelativeLayout(相对布局)是一个ViewGroup(视图组),负责显示子视图中相对位置的元素。视图的位置可以被指定为相对同级组件(如向左侧或低于特定组件)或相对位置于RelativeLayout区(如底部对齐,中心左)。
RelativeLayout是用于设计用户界面的一个很强大的组件,因为它可以避免嵌套ViewGroups组件。如果你使用多个嵌套的LinearLayout组,您可能能用一个单一RelativeLayout来取代他们。
  1. 创建一个新的项目名为HelloRelativeLayout。
  2. 打开 res/layout/main.xml文件并插入以下代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Type here:"/>
    <EditText
        android:id="@+id/entry"
        android:layout_width="fill_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_below,layout_alignParentRight和layout_toLeftOf。当使用一个RelativeLayout,你可以使用这些属性来指定你想要放置每个View。其中的每个属性定义了一个相对不同的位置。某些属性使用了其他组件的资源ID来定义自己的相对位置。比如,最后一个Button使用了 “id/ok” 来定义自己的位置居左和顶对齐于前一个Button(id是ok) 的位置。所有的相对布局属性都可以用 RelativeLayout.LayoutParams 来定义。

3. 现在打开 HelloRelativeLayout.java 然后确认在onCreated()方法里有载入 res/layout/main.xml布局,代码如下:

public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
}

该setContentView(int)方法加载该活动的布局文件,由指定的资源ID – R.layout.main来寻找其地址 res/layout/main.xml。

4. 运行该项目,你应该该看到以下的视图:

文章转载/翻译自:http://developer.android.com/resources/tutorials/views/hello-relativelayout.html

您可能也喜欢

与大家分享点什么吧: