創建XML布局
“entry > src > main > resources > base”,在base文件夾下創建一個目錄,命名為“layout”
在layout目錄下創建一個File,命名為“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="25vp"/>
<Button
ohos:id="$+id:button"
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。
@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) {
// 此處添加按鈕被點擊需要執行的操作
}
});
}
}
如果DevEco Studio提示Layout_first_layout錯誤,點擊菜單欄的“Build”,選擇“Build App(s)/Hap(s) > Build Debug Hap(s) ”,即可消除報錯。