Android布局—相對布局(Relative Layout)

來源:互聯網
上載者:User

本文譯自:http://developer.android.com/guide/topics/ui/layout/relative.html

RelativeLayout是一個用相對位置來顯示子View的View組。每個View的位置可以相對與相鄰元素來指定(如相對與另一個View的左邊或底邊),或者相對於父RelativeLayout地區位置來指定(如底部對齊,中央偏左)。

RelativeLayout是用於設計使用者介面的非常強大的工具,因為它可以消除嵌套的View組,並讓你的布局層次平面化,這樣可以改善效能。如果你發現你使用了幾個嵌套的LinearLayout組,那麼你就可以使用一個單一的RelativeLayout來替代。

View定位

RelativeLayout會讓子View相對與父View或相鄰的View(通過ID來指定)來指定它們的位置。因此你讓兩個元素沿著左邊框來對齊,或者是上下中央對齊,等等。預設情況,所有的子View都會被繪製在布局的左上方,因此你必須使用來自RelativeLayout.LayoutParams中的各種布局屬性來定義每個View的位置。

以下是RelativeLayout中包含的有效布局屬性:

android:layout_alignParentTop

   如果該屬性值是“true”,那麼該View的上邊緣要跟它的父View的上邊緣來匹配。

android:layout_centerVertical

   如果該屬性值是“true”,那麼在該View父View內部,它會垂直置中。

android:layout_below

   該View的上邊緣位於用資源ID指定的View的下面。

android:layout_toRightOf

   該View的左邊緣位於用資源ID指定的View的右邊。

這些只是一些例子,所有的布局屬性在文檔RelativeLayout.LayoutParams中。

 

每個布局屬性值可能是一個相對與其父RelativeLayout的布爾值,也可能是在布局內相鄰View的ID。

在你的XML布局中,可以按照任意的順序來聲明對布局中另一個View的依賴。例如,你可以聲明View1位於View2的下方,即使View2在布局層次中是最後被聲明的。以下樣本示範了這種情境。

<?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"

   
android:paddingLeft="16dp"

   
android:paddingRight="16dp" >

   
<EditText

       
android:id="@+id/name"

       
android:layout_width="fill_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>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.