第四章 - HarmonyOS鸿蒙开发:3分钟Java代码编写第二个页面

作者:孔壹学院、程序咖创始人黎跃春。

免费系统学习请移步:https://chengxuka.com

在上一节中,我们用XML的方式编写了一个包含文本和按钮的页面。这一节我们使用代码的方式编写第二个页面。

  • 打开src/main/java/com/example/myapplication/slice/MainAbilitySlice.java文件,将下面的代码拷贝到里面。
package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
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 ohos.agp.components.DependentLayout.LayoutConfig;

public class MainAbilitySlice 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("www.chengxuka.com");
        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); // 加载XML布局
    }
}
  • 运行项目看效果。

入门系列

猜你喜欢

转载自blog.csdn.net/liyuechun520/article/details/116998844
今日推荐