本期,我们来从零开始通过代码实现在第一个页面点击按钮跳转到第二个页面。
打开第一个页面的“MainAbilitySlice.java”文件,重写onStart()方法添加按钮的响应逻辑,实现点击按钮跳转到下一页,示例代码如下:
package com.example.myapplication.slice;
import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_main_layout);
Button button = (Button) findComponentById(ResourceTable.Id_button);
if (button != null) {
// 为按钮设置点击回调
button.setClickedListener(new Component.ClickedListener() {
@Override
public void onClick(Component component) {
Intent secondIntent = new Intent();
// 指定待启动FA的bundleName和abilityName
Operation operation = new Intent.OperationBuilder()
.withDeviceId("")
.withBundleName("com.example.myapplication")
.withAbilityName("com.example.myapplication.SecondAbility")
.build();
secondIntent.setOperation(operation);
startAbility(secondIntent); // 通过AbilitySlice的startAbility接口实现启动另一个页面
}
});
}
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
注意事项,请将com.example.myapplication替换成您的项目名称
.withBundleName("com.example.myapplication")
.withAbilityName("com.example.myapplication.SecondAbility")
群名称:harmonyos鸿蒙技术交流
群 号:856567895