鸿蒙开发基础(五)XML创建布局

创建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) ”,即可消除报错。

原文地址:https://www.cnblogs.com/cnyl/p/13944639.html