1. 在“Project”窗口,打开“entry > src > main > java”,右键点击“com.example.myapplication”文件夹,选择“New > Ability > Empty Page Ability(Java)”。
  2. 配置Ability时,将“Page Name”设置为“SecondAbility”,点击“Finish”。创建完成后,可以看到新增了“SecondAbility”和“SecondAbilitySlice”文件。
    编写第二个页面。
    打开“SecondAbilitySlice.java”文件,添加一个文本,示例代码如下:

package com.example.myapplication.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;


import ohos.agp.colors.RgbColor;
import ohos.agp.components.DependentLayout;
 import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;

import static ohos.agp.components.DependentLayout.LayoutConfig.MATCH_PARENT;
import static ohos.agp.components.DependentLayout.LayoutConfig.MATCH_CONTENT;
 
  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("Hi there");
	        text.setWidth(MATCH_PARENT);
        text.setTextSize(100);
        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);
	    }
	}

想入门鸿蒙开发又怕花冤枉钱?别错过!现在能免费系统学 – 从 ArkTS 面向对象核心的类和对象、继承多态,到吃透鸿蒙开发关键技能,还能冲刺鸿蒙基础 +高级开发者证书,更惊喜的是考证成功还送好礼!快加入我的鸿蒙班,一起从入门到精通,班级链接:点击免费进入

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新

更多推荐