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

致读者

推荐学习网站: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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值