Chapter 5 - HarmonyOS development: page jump in 3 minutes

Author: Li Yuechun, founder of Kongyi Academy and Programming Cafe.

For free system learning, please go to: https://chengxuka.com

In the above two chapters, we learned how to implement two different UI layouts through XML layout and Java code layout. In this chapter, we then 3分钟XML布局编写第一个页面implement the jump between the two pages.

1. SecondAbilitySlice.javaPage creation

src/main/java/com/example/myapplication/sliceCreate the file below and SecondAbilitySlice.javacopy the following code into SecondAbilitySlice.javait.

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. Modify the `MainAbilitySlice.java' file, add the response logic of the button, and realize clicking the button to jump to the next page. The sample code is as follows:

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. The operation effect is as follows

Entry Series

Guess you like

Origin blog.csdn.net/liyuechun520/article/details/116998866
Recommended