常用控件 02 佈局 Layout

1.寫xml文件:

最外層元素必須是 View 或者 ViewGroup,如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              android:orientation="vertical" >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Hello, I am a TextView" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
</LinearLayout>
保存爲.xml格式文件,並存放在項目的 res/layout/ 下。


2.加載xml文件:

調用 setContentView() 方法。如:

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

3.屬性(Attributes):

Attributes 分爲兩種:從 root View 繼承而來的屬性(如 ID );佈局參數( layout parameters )用於描述特定的方面;
1>ID:

1)  添加 ID資源:

android:id="@+id/my_button"
@ 表示要求xml語句解析器將後邊的部分解析爲 ID資源,+ 表示該資源需要創建並添加到 R.java 文件中;

使用 ID 資源時:

android:id="@android:id/empty"

2)佈局參數(layout Parameters):

格式:layout_something ;

每一個 ViewGroup 類都實現了繼承自 ViewGroup.LayoutParams 類的內部類, 如 FrameLayout.LayoutParams, GridLayout.LayoutParams 等;

每個 LayoutParams 至少有兩屬性: android:layout_height 和 android:layout_width,其值通常是:具體數值,MATCH_PARENT,WRAP_CONTENT;

3)佈局位置(Layout Position):

view 是一個矩形,其位置用 left 和 top 的座標,加上 width 和 hight 兩個維度表示。單位爲 pixel (像素);
可以調用 getLeft() 和 getTop() 方法來獲得位置;

3常見的佈局:

ViewGroup 的每一個子類都是一種layout;
層次越少,顯示速度越快;

1)Linear Layout :

使所有子元素按水平或垂直方向排成一排,方向由 android:orientation 屬性決定。
水平方向的每行只有一個元素,垂直方向的,其高度由最高的元素加上 padding 決定;
可以使用 margins 來定義元素之間的間隔,用 gravity (right, center, 或者 left)來確定對齊方式;
用 android:layout_weight 屬性來確定該元素的重要程度,默認爲0,按數值比例來劃分剩下的空閒空間;

2)Relative Layout:
每一個 View 的位置都由與其他元素之間的相互關係來確定;
每一個 View 的位置默認是在左上角,所以每個元素都需要指定位置;
所有的屬性都可以在 RelativeLayout.LayoutParams 中找到,如:android:layout_alignParentTop,android:layout_centerVertical,android:layout_below,android:layout_toRightOf等;
可以不按照出現的順序來定義相互之間的關係,如可以先讓A below B,然後再聲明B。


當佈局的內容是動態的或者無法事先確定的時候,可以用 AdapterView 的子類來在運行過程中填充layout。
Adapter 將獲得的數據(從資源文件或者數據庫)轉換成一個 View 添加到 AdapterView 中。

常見的 AdapterView 的子類有: GridView, ListView, Spinner, StackView等

3)List View

4)   Grid View






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章