歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android SDK Tutorials系列 - Hello Views - Relative Layout

Android SDK Tutorials系列 - Hello Views - Relative Layout

日期:2017/3/1 10:56:38   编辑:Linux編程

Relative Layout

RelativeLayoutViewGroup 的一種,它裡面包含的View按照相對位置進行排列,可以指定一個View跟相鄰View的位置關系(例如:在某個View的左邊,或者下面);或者指定這個View相對於RelativeLayout這個容器的位置(例如底部,或者左邊中間)。

RelativeLayout是一個很強大的工具,在設計用戶界面的時候可以消除嵌套的ViewGroup。如果你在嵌套使用LinearLayout,你應該可以用單個的RelativeLayout來取代它。

  1. 創建一個工程:HelloRelativeLayout
  2. 打開res/layout/main.xml 並修改如下:
     
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <RelativeLayout xmlns:Android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="fill_parent"
    4. android:layout_height="fill_parent">
    5. <TextView
    6. android:id="@+id/label"
    7. android:layout_width="fill_parent"
    8. android:layout_height="wrap_content"
    9. android:text="Type here:"/>
    10. <EditText
    11. android:id="@+id/entry"
    12. android:layout_width="fill_parent"
    13. android:layout_height="wrap_content"
    14. android:background="@android:drawable/editbox_background"
    15. android:layout_below="@id/label"/>
    16. <Button
    17. android:id="@+id/ok"
    18. android:layout_width="wrap_content"
    19. android:layout_height="wrap_content"
    20. android:layout_below="@id/entry"
    21. android:layout_alignParentRight="true"
    22. android:layout_marginLeft="10dip"
    23. android:text="OK" />
    24. <Button
    25. android:layout_width="wrap_content"
    26. android:layout_height="wrap_content"
    27. android:layout_toLeftOf="@id/ok"
    28. android:layout_alignTop="@id/ok"
    29. android:text="Cancel" />
    30. </RelativeLayout>

    關注每一個android:layout_* 屬性,例如layout_below, layout_alignParentRight, 還有layout_toLeftOf。 使用RelativeLayout的時候,用這些屬性來設置每個View的位置。這些屬性的每一個都定義了一種相對位置。有些屬性使用相鄰View的資源ID來定義自己的相對位置。例如,最後一個Button,被擺放在資源ID ok (這是前一個Button)的左邊,並和它上對齊。

    所有的布局屬性都定義在 RelativeLayout.LayoutParams.


  3. 確保你在onCreate() 方法裝載了這個布局:

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

    setContentView(int) 方法裝載這個Activity的布局文件,資源ID — R.layout.main 指向res/layout/main.xml布局文件。

  4. 運行應用。

應該能看到下面的畫面:




返回 Android SDK Tutorials系列 - Hello Views
Copyright © Linux教程網 All Rights Reserved