> 文档中心 > HarmonyOS学习路之开发基础——快速入门(创建另一个页面)

HarmonyOS学习路之开发基础——快速入门(创建另一个页面)


创建另一个页面

在上一节中,我们用XML的方式编写了一个包含文本和按钮的页面。为了帮助开发者熟悉在代码中创建布局的方式,接下来我们使用代码的方式编写第二个页面。

在“Project”窗口,打开“entry > src > main > java > com.example.myapplication”,右键点击“slice”文件夹,选择“New > Java Class”,命名为“SecondAbilitySlice”,单击回车键。
第二个页面上有一个文本。在上一步创建的“SecondAbilitySlice”文件中,添加一个Text,示例代码如下:

import ohos.aafwk.ability.AbilitySlice;import ohos.aafwk.content.Intent;import ohos.agp.colors.RgbColor;import ohos.agp.components.DependentLayout;import ohos.agp.components.DependentLayout.LayoutConfig;import ohos.agp.components.Text;import ohos.agp.components.element.ShapeElement;import ohos.agp.utils.Color;public class SecondAbilitySlice extends AbilitySlice {    @Override    public void onStart(Intent intent) { super.onStart(intent); // 声明布局 DependentLayout myLayout = new DependentLayout(this); // 设置布局宽高 myLayout.setWidth(LayoutConfig.MATCH_PARENT); myLayout.setHeight(LayoutConfig.MATCH_PARENT); // 设置布局背景为白色 ShapeElement background = new ShapeElement(); background.setRgbColor(new RgbColor(255, 255, 255)); myLayout.setBackground(background); // 创建一个文本 Text text = new Text(this); text.setText("Hi there"); text.setWidth(LayoutConfig.MATCH_PARENT); text.setTextSize(100); text.setTextColor(Color.BLACK); // 设置文本的布局 DependentLayout.LayoutConfig textConfig = new DependentLayout.LayoutConfig(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT); textConfig.addRule(LayoutConfig.CENTER_IN_PARENT); text.setLayoutConfig(textConfig); myLayout.addComponent(text); super.setUIContent(myLayout);    }}