版面配置資源可定義活動或 UI 元件中的架構。
- 檔案位置:
res/layout/filename.xml
系統會把檔案名稱當做資源 ID。- 編譯資源資料類型:
View
(或子類別) 資源的資源指標。- 資源參照:
-
Java:
R.layout.filename
XML:@[package:]layout/filename
- 語法:
-
<?xml version="1.0" encoding="utf-8"?> <ViewGroup xmlns:android="http://schemas.android.com/apk/res/android" android:id="@[+][package:]id/resource_name" android:layout_height=["dimension" | "match_parent" | "wrap_content"] android:layout_width=["dimension" | "match_parent" | "wrap_content"] [ViewGroup-specific attributes] > <View android:id="@[+][package:]id/resource_name" android:layout_height=["dimension" | "match_parent" | "wrap_content"] android:layout_width=["dimension" | "match_parent" | "wrap_content"] [View-specific attributes] > <requestFocus/> </View> <ViewGroup > <View /> </ViewGroup> <include layout="@layout/layout_resource"/> </ViewGroup>
注意:根元素可以是
ViewGroup
、View
或<merge>
元素,但必須只能有一個根元素,而且此根元素必須包含xmlns:android
屬性及android
命名空間,如圖所示。 - 元素:
-
android:id
的值如果是 ID 值,通常都會使用以下語法格式:
"@+id/name"
。加號 (+
) 表示這是新的資源 ID,而且aapt
工具會在R.java
類別中建立新的資源整數 (如果還沒有)。舉例來說:<TextView android:id="@+id/nameTextbox"/>
nameTextbox
名稱現在是此元素附加的資源 ID。然後您就可以參照TextView
,且其 ID 在 Java 中會建立關聯:Kotlin
val textView: TextView? = findViewById(R.id.nameTextbox)
Java
TextView textView = findViewById(R.id.nameTextbox);
此程式碼會傳回
TextView
物件。但是如果您已定義 ID 資源 (且該 ID 資源尚未使用),您就可以在
android:id
中排除加號,以套用該 ID至View
。android:layout_height
和android:layout_width
:您可以使用任何 Android 支援的維度單位來表達高度和寬度的值 (px、dp、sp、pt、in、mm),或者也可以使用下列關鍵字:
值 說明 match_parent
依照父項元素的維度設定維度。已在 API 級別 8 中新增,藉此淘汰 fill_parent
。wrap_content
僅依照為符合此元素內容所需的大小設定維度。 自訂檢視畫面元素
您可以建立自訂的
View
和ViewGroup
元素,然後以與標準版面配置元素相同的方式套用至您的版面配置。您也可以指定 XML 元素中支援的屬性。詳情請參閱自訂元件開發人員指南。 - 例如:
- XML 檔案儲存在
res/layout/main_activity.xml
:<?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="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>
此應用程式程式碼會在
onCreate()
方法中載入Activity
的版面配置: -
Kotlin
public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) }
Java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); }
- 另請參閱: