第五章 - 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. 运行效果如下

入门系列

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黎跃春

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值