美文网首页
鸿蒙系统开发入门示例(HarmonyOs入门示例)

鸿蒙系统开发入门示例(HarmonyOs入门示例)

作者: k8s程序员 | 来源:发表于2021-02-08 10:45 被阅读0次

    致读者

    推荐学习网站:https://www.hellodemos.com

    编写第一个页面

    1、在“Project”窗口,点击 “entry > src > main > resources > base > layout”,打开“ability_main.xml”文件。

    image.png

    2、在“ability_main.xml”文件中创建一个文本和一个按钮,示例代码如下:

    <?xml version="1.0" encoding="utf-8"?>
    <DependentLayout
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        ohos:width="match_parent"
        ohos:height="match_parent"
        ohos:background_element="#FFFFFF">
        <Text
            ohos:id="$+id:text"
            ohos:width="match_content"
            ohos:height="match_content"
            ohos:text="Hello World"
            ohos:text_color="#000000"
            ohos:text_size="32fp"
            ohos:center_in_parent="true"/>
        <Button
            ohos:id="$+id:button"
            ohos:width="match_content"
            ohos:height="match_content"
            ohos:text="Next"
            ohos:text_size="19fp"
            ohos:text_color="#FFFFFF"
            ohos:top_padding="8vp"
            ohos:bottom_padding="8vp"
            ohos:right_padding="70vp"
            ohos:left_padding="70vp"
            ohos:background_element="$graphic:background_button"
            ohos:center_in_parent="true"
            ohos:align_parent_bottom="true"
            ohos:bottom_margin="40vp"/>
    </DependentLayout>
    

    3、上述按钮的背景是通过“background_button”来显示的。右键点击“graphic”文件夹,选择“New > File”,命名为“background_button.xml”

    image.png

    “background_button.xml”的示例代码如下(如果DevEco Studio提示xmlns字段错误,请忽略,不影响后续操作):

    <?xml version="1.0" encoding="utf-8"?>
    <shape
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        ohos:shape="rectangle">
        <corners
            ohos:radius="100"/>
        <solid
            ohos:color="#007DFF"/>
    </shape>
    

    4、在“Project”窗口,选择“entry > src > main > java > com.example.myapplication > slice” ,打开“MainAbilitySlice.java”文件,使用setUIContent方法加载XML布局,示例代码如下:

    package com.example.myapplication.slice;
    
    
    import com.example.myapplication.ResourceTable;
    import ohos.aafwk.ability.AbilitySlice;
    import ohos.aafwk.content.Intent;
    
    
    public class MainAbilitySlice extends AbilitySlice {
        @Override
        public void onStart(Intent intent) {
            super.onStart(intent);
            super.setUIContent(ResourceTable.Layout_ability_main); // 加载XML布局
        }
    
    
        @Override
        public void onActive() {
            super.onActive();
        }
    
    
        @Override
        public void onForeground(Intent intent) {
            super.onForeground(intent);
        }
    }
    

    说明:
    如果DevEco Studio提示Layout_ability_main错误,点击菜单栏的“Build”,选择“Build App(s)/Hap(s) > Build Debug Hap(s) ”,即可消除报错。

    5、请参考应用运行效果如图所示

    image.png

    相关文章

      网友评论

          本文标题:鸿蒙系统开发入门示例(HarmonyOs入门示例)

          本文链接:https://www.haomeiwen.com/subject/ttuxxltx.html