XML声明布局的方式更加简便直观。每一个Component和ComponentContainer对象大部分属性都支持在XML中进行设置,它们都有各自的XML属性列表。某些属性仅适用于特定的组件,例如:只有Text支持“text_color”属性,不支持该属性的组件如果添加了该属性,该属性则会被忽略。具有继承关系的组件子类将继承父类的属性列表,Component作为组件的基类,拥有各个组件常用的属性,比如:ID、布局参数等。
ID
ohos:id="$+id:text"
在XML中使用此格式声明一个对开发者友好的ID,它会在编译过程中转换成一个常量。尤其在DependentLayout布局中,组件之间需要描述相对位置关系,描述时要通过ID来指定对应组件。
布局中的组件通常要设置独立的ID,以便在程序中查找该组件。如果布局中有不同组件设置了相同的ID,在通过ID查找组件时会返回查找到的第一个组件,因此尽量保证在所要查找的布局中为组件设置独立的ID值,避免出现与预期不符合的问题。
布局参数
ohos:width="20vp"
ohos:height="10vp"
与代码中设置组件的宽度和高度类似,在XML中它们的取值可以是:
- 具体的数值:10(以像素为单位)、10vp(以屏幕相对像素为单位)。
- match_parent:表示组件大小将扩展为父组件允许的最大值,它将占据父组件方向上的剩余大小。
- match_content:表示组件大小与它的内容占据的大小范围相适应。
创建XML布局文件
- 在DevEco Studio的Project窗口,打开“entry > src > main > resources > base”,右键点击“layout”文件夹,选择“New > Layout Resource File”,命名为“first_layout”。

打开新创建的first_layout.xml布局文件,修改其中的内容,对布局和组件的属性和层级进行描述。
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:height="match_parent"
ohos:orientation="vertical"
ohos:padding="32">
<Text
ohos:id="$+id:text"
ohos:width="match_content"
ohos:height="match_content"
ohos:layout_alignment="horizontal_center"
ohos:text="My name is Text."
ohos:text_size="25fp"/>
<Button
ohos:id="$+id:button"
ohos:margin="50"
ohos:width="match_content"
ohos:height="match_content"
ohos:layout_alignment="horizontal_center"
ohos:text="My name is Button."
ohos:text_size="50"/>
</DirectionalLayout>
加载XML布局
在代码中需要加载XML布局,并添加为根布局或作为其他布局的子Component。
//请根据实际工程/包名情况引入
package com.example.myapplication.slice;
import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
public class ExampleAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// 加载XML布局作为根布局
super.setUIContent(ResourceTable.Layout_first_layout);
Button button = (Button) findComponentById(ResourceTable.Id_button);
if (button != null) {
// 设置组件的属性
ShapeElement background = new ShapeElement();
background.setRgbColor(new RgbColor(0, 125, 255));
background.setCornerRadius(25);
button.setBackground(background);
button.setClickedListener(new Component.ClickedListener() {
@Override
// 在组件中增加对点击事件的检测
public void onClick(Component component) {
// 此处添加按钮被点击需要执行的操作
}
});
}
}
}