目录:

3.1 第一个鸿蒙应用实现需求

编写两张页面,实现在第一张页面点击按钮跳转到第二张页面。在Java UI框架中,提供了两种编写布局的方式:在XML中声明UI布局和在代码中创建布局。这两种方式创建出的布局没有本质差别,都是我们需要熟悉方式,所以我们将通过XML的方式布局第一张页面,然后再通过代码的方式布局第二张页面。

3.2 用XML布局第一张页面打开layout下面的“ability_main.xml”文件

在“ability_main.xml”文件中创建一个文本和一个按钮<?xml version="1.0" encoding="utf-8"?>

xmlns:ohos="http://schemas.huawei.com/res/ohos"

ohos:width="match_parent"

ohos:height="match_parent"

ohos:background_element="#000000">

ohos:id="$+id:text"

ohos:width="match_content"

ohos:height="match_content"

ohos:text="Hello World"

ohos:text_color="white"

ohos:text_size="32fp"

ohos:center_in_parent="true"/>

ohos:id="$+id:button"

ohos:width="match_content"

ohos:height="match_content"

ohos:text="Next"

ohos:text_size="19fp"

ohos:text_color="white"

ohos:top_padding="8vp"

ohos:bottom_padding="8vp"

ohos:right_padding="80vp"

ohos:left_padding="80vp"

ohos:background_element="$graphic:background_button"

ohos:below="$id:text"

ohos:horizontal_center="true"

/>

创建按钮的背景

按钮的背景是通过“background_button”来指定的。右键点击“graphic”文件夹,选择“New > File”,命名为“background_button.xml”。<?xml version="1.0" encoding="utf-8"?>

3.3 用编程的方式布局第二张页面创建Feature Ability

代码编写界面public class SecondAbilitySlice extends AbilitySlice {

@Override

public void onStart(Intent intent) {

super.onStart(intent);

// 声明布局

DependentLayout myLayout = new DependentLayout(this);

// 设置页面布局大小和背景色

myLayout.setWidth(MATCH_PARENT);

myLayout.setHeight(MATCH_PARENT);

ShapeElement element = new ShapeElement();

element.setRgbColor(new RgbColor(255, 255, 255));

myLayout.setBackground(element);

// 创建一个文本

Text text = new Text(this);

text.setText("Nice to meet you.");

text.setTextSize(55);

text.setTextColor(Color.BLACK);

// 设置文本的布局

DependentLayout.LayoutConfig textConfig =

new DependentLayout.LayoutConfig(MATCH_CONTENT,MATCH_CONTENT);

textConfig.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);

text.setLayoutConfig(textConfig);

myLayout.addComponent(text);

super.setUIContent(myLayout);

}

@Override

public void onActive() {

super.onActive();

}

@Override

public void onForeground(Intent intent) {

super.onForeground(intent);

}

}

作者:zhonghongfa

想了解更多内容,请访问: 51CTO和华为官方战略合作共建的鸿蒙技术社区https://harmonyos.51cto.com

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐