布局资源定义了 Activity
或 UI 组件的 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。然后您可以在 Java 中引用与该 ID 关联的TextView
Kotlin
val textView: TextView? = findViewById(R.id.nameTextbox)
Java
TextView textView = findViewById(R.id.nameTextbox);
此代码返回
TextView
对象。但是,如果您已经定义了ID 资源,并且它尚未被使用,那么您可以通过在
android: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); }
- 另请参阅