第五章 - HarmonyOS鸿蒙开发:3分钟实现页面跳转

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

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

上面的两章节我们学会了如何通过XML布局和Java代码布局实现两种不同的UI布局,在这一章节中,我们接着3分钟XML布局编写第一个页面来实现两个页面之间的跳转。

1. SecondAbilitySlice.java页面创建

src/main/java/com/example/myapplication/slice下面创建SecondAbilitySlice.java文件,并将下面的代码拷贝到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 ohos.agp.components.DependentLayout.LayoutConfig;

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("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);
    }
}

2. 修改`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.components.Button;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Button button = (Button) findComponentById(ResourceTable.Id_button);

        // 点击按钮跳转至第二个页面
        button.setClickedListener(listener -> present(new SecondAbilitySlice(), new Intent()));
    }
}

3. 运行效果如下

入门系列

猜你喜欢

转载自blog.csdn.net/liyuechun520/article/details/116998866