close

LinearLayout
    螢幕的最外層,只要定義元件皆以水平(horizontal)或垂直(vertical)排列。

元件的高度與寬度

Android的所有元件都具備兩個屬性,也就是元件的高與寬,屬性名稱為「layout:height」與「layout:width」,許多人直覺想要以螢幕的畫素為元件訂定個別的高度與寬度,其實,為元件訂定固定的高與寬是不適合的,因為Android手機產品非常多元,有的手機的解析度是480×720,有的是640×960、640×1136、1080×1920或甚至1440×2560,如此眾多的差異性。假設我們的APP訂的元件大小是固定的,那是無法滿足所有的螢幕需求的。因此,Android建議開發者在訂定元件大小時,若希望只占用元件內容資料時,使用「wrap_content」值,當想要元件占滿所在區域可用空間時,使用「match_parent」值,筆者使用上節的LinearLayout垂直配置的範例,說明如下。

符合元件內容物-wrap_content

       意義是元件只占可顯示其內容物的大小,代表元件的高與度都只占必要的空間

以元件所在的容器為主-match_parent

       意義是所在容器有多大就占多大

元件的間距-margin

每一個元件都可指定其上下左右與其他元件的距離,稱之為「Margin」間距,「android:layout_margin」為其屬性名稱,可以統一設定四個方向的間距,亦可個別設定。

元件的對齊

為元件設定「layout:gravity」屬性,可決定元件在容器中向那個方位靠攏

另一個與layout:gravity屬性很像的屬性為「gravity」,假如在一個版面中有很多個元件,想要每個元件都以同一種方式對齊,要一個個去設定實在太繁複了,「gravity」屬性提供給版面配置或容器統一設定裏面元件的對齊方式,只要設定版面即可。請到LinearLayout,設定gravity屬性, 例如所有在LinearLayout中的元件都要水平置中。

LinearLayout中的權重weight

當我們在LinearLayout中放入多個元件時,可利用屬性「weight」權重,為元件分配不同的權重值,其預設值為0。透過分別設定在LinearLayout內的元件的權值值,可依權重分配元件可以占用的空間,

例如: 三個Button元件的權重值都是1.0 ,將會平均分配空間

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="BUTTON1" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="BUTTON2" />
 
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="BUTTON3" />
</LinearLayout>
 

RelativeLayout

RelativeLayout是Android Studio在產生Activity時使用的預設Layout,在此版面的元件都需要參考一個對象,這個對象可以是任一個元件或是元件所在位置的元件,在本例也就是面版本身(parent),也可稱為元件所在容器。

       元件相對位置屬性有幾個常用的屬性,對象為父元件(容器)的相關屬性:
  • android:layout_alignParentTop:若為true,對齊所在容器的頂邊
  • android:layout_alignParentBottom:若為true,對齊所在容器的下緣
  • android:layout_alignParentLeft:若為true,對齊所在容器的左邊緣
  • android:layout_alignParentRight:若為true,對齊所在容器的右邊緣
  • android:layout_alignParentCenter:若為true,元件放在容器的中央

當對象為一般元件時的相關屬性:

  • android:layout_above:元件放在對象之上
  • android:layout_below:元件放在對象之下
  • android:layout_toLeftOf:元件的右邊緣對齊對象的左邊緣
  • android:layout_toRightOf:元件的左邊緣對齊對象的右邊緣
  • android:layout_alignTop:元件的上緣對齊對象的上緣
  • android:layout_alignBottom:元件的下緣對齊對象的下緣
  • android:layout_alignLeft:元件的左邊緣對齊對象的左邊緣
  • android:layout_alignRight:元件的右邊緣對齊對象的右邊緣
  • android:layout_centerHorizontal:元件水平置中
  • android:layout_centerVertical:元件垂直置中

 

 

arrow
arrow
    文章標籤
    Android 元件的屬性
    全站熱搜

    stanley 發表在 痞客邦 留言(0) 人氣()