View與ViewGroup概念

在Android中,所有的用戶界面元素都是由View和ViewGroup的所組成。View是繪製在螢幕上能與用戶互動的對象。而ViewGroup則是一個用於存放其他View(和ViewGroup)的佈局容器!

Android提供了一個View和ViewGroup子類的集合,集合中提供了一些常用的輸入控制元件(比如按鈕和文字輸入框)和各種的佈局模式(比如線性或相對佈局)

編寫XML

利用Android 的XML 詞彙,如果在HTML 中創建包含嵌套元素的相同方式設計UI 佈局及其包含的元素。

每個佈局文件必須只包含一個根元素,並且該元素需為 View 或 ViewGroup 。定義根元素之後,即可再添加其他佈局或控制元件等子元素,構建完整的介面結構。例如,以下這個XML佈局使用垂直LinearLayout來儲存一個TextView和一個Button

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_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"
              tools:text="Hello!!!!" />

    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />

</LinearLayout

常用元件屬性

ID

任何元件都可以設定ID屬性,此 ID 為此 View 的唯一標識。編譯程式後,此ID將作為整型數引用。
在佈局XML文件中,使用id屬性中為該ID賦予字符串值。

XML標記內部的ID語法是:

android : id = "@+id/my_button"

字串開頭處的@符號標示XML需進行解析並展開ID字串的其餘部分,並將其標識為ID資源。
加號(+)表示這是一個新的資源名稱,必須建立該名稱並將其添加到資源文件(R.java)內。
Android還提供了許多預設ID資源。引用Android資源ID時,不需要加號,但必須添加android如下所示:

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

參考Android預先定義的資源ID,可至下列檔案查詢:sdk\platforms\android-[X]\data\res\values

佈局參數

通常名稱為layout_[something] XML 布局属性可為 View 定義布局参数。

例如所有的 ViewGroup 都包含寬度和高度的設定:layout_widthlayout_height,且必需定義。除此之外,還有如外邊距設定:layout_margin,在父框架的位置:layout_gravity等等…

layout_margin指定元件上下左右的外部邊界,即與其他元件的間距

layout_marginLeft指定元件的左邊界

layout_marginRight指定元件的右邊界

layout_marginTop指定元件的上邊界

layout_marginBottom指定元件的下邊界

padding指定元件的內部邊距

paddingLeft指定元件的內部左邊距

paddingRight指定元件的內部右邊距

paddingTop指定元件的內部上邊距

paddingBottom指定元件的內部下邊距

results matching ""

    No results matching ""