Android应用程序用户界面(五)

来源:互联网 发布:软件时间限制工具 编辑:程序博客网 时间:2024/06/06 17:41

相对视图是以相对位置显示子视图的视图组。每个视图的位置可以以相对于其兄弟元素的方式指定(例如在某个视图的左边或下边),或者以相对于父视图区域的方式(例如底对齐、左对齐或中心对齐等)。

相对视图
相对布局是设计用户界面的一个非常强大的工具,因为它能消除嵌套的视图组,并且保持你的布局层次是平的,这会提高应用程序的性能。如果你发现自己使用了几个相互嵌套的线性布局组,那么你可能可以使用单独一个相对视图来代替它。

放置视图

相对视图让子视图以相对于它们的父视图或其他子视图(以ID引用)的方式指定它们的位置。因此,你可以让两个元素右边界对齐,或者让一个在另一个下面,在屏幕中央,或者在屏幕的左边中央等等。 默认情况下,所有的子视图都绘制在布局的左上方,因此你必须使用来自于RelativeLayout.LayoutParameters的各种各样的布局属性定义每个视图的位置。

在相对视图中视图具有大量布局属性,包括:

  • android:layout_alignParentTop。如果这个值为true,那么这个视图的顶边和父视图的顶边重合。
  • android:layout_centerVertical。如果这个值为true,那么这个视图将位于父视图的竖直方向的中心。
  • android:layout_below。将该子视图的顶边放在由资源ID指定的视图的下边。
  • android:layout_toRightOf。将该子视图的左边放置在由资源ID指定的视图的右边。
    这只是一些属性的例子,所有的布局属性都在RelativeLayout.Layout Params的文档中。

每个布局属性的值要么是布尔值支持相对于父视图的布局位置,要么是一个引用布局中另一个视图的ID,该视图应该相对于这个视图放置。

在你的XML布局中,依赖的视图必须要先声明。例如,如果要通过引用“view2”的ID将“view1”放置在“view2”的下边,那么“view2”元素必须要在“view1”之前声明。(原文中说任意顺序都可以,在测试下例时出现问题,发现必须要先声明引用的元素

注意:布局文件的名称必须都是小写字母、数字和下划线,不能包含大写字母。

示例

布局文件

<?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/times"      android:layout_width="96dp"      android:layout_height="wrap_content"      android:layout_below="@id/name"      android:layout_alignParentRight="true"/>  <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"/>  <Button      android:layout_width="96dp"      android:layout_height="wrap_content"      android:layout_below="@id/times"      android:layout_alignParentRight="true"      android:text="@string/done"/></RelativeLayout>

字符串值

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">LayoutStudyActivity</string>    <string name="to">To</string>    <string name="subject">Subject</string>    <string name="message">Message</string>    <string name="send">Send</string>    <string name="reminder">Reminder name</string>    <string name="done">Done</string></resources>

java代码

package lemon.learnandroid;import android.app.Activity;import android.os.Bundle;public class LayoutStudyActivity extends Activity{    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main_relativelayout);    }}

示例

原文

http://wear.techbrood.com/guide/topics/ui/layout/relative.html

0 0