电子说
基于Stage模型下的UIAbility开发,实现UIAbility内和UIAbility间页面的跳转。包含如下功能:
最终效果图如下:
完成本篇Codelab我们首先要完成开发环境的搭建,本示例以RK3568开发板为例,参照以下步骤进行:
gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]本篇Codelab只对核心代码进行讲解,完整代码可以直接从gitee获取。
├──device/src/main/ets // device模块的代码区
│ ├──pages
│ │ ├──Index.ets // SecondAbility的Index页面
│ │ └──Second.ets // SecondAbility的Second页面
│ ├──secondability
│ │ └──SecondAbility.ets // 程序入口类
├──device/src/main/resources // device模块的资源文件目录
├──entry/src/main/ets // entry模块的代码区
│ ├──common
│ │ ├──constants
│ │ │ ├──CommonConstants.ets // 公共常量类
│ │ │ └──StyleConstants.ets // 样式常量类
│ │ ├──utils
│ │ │ ├──GlobalContext.ets // 全局变量控制类
│ │ │ └──Logger.ets // 日志打印类
│ ├──entryability
│ │ └──EntryAbility.ts // 程序入口类
│ ├──model
│ │ └──ButtonClickMethod.ets // 按钮点击后调用的方法类
│ ├──pages
│ │ ├──Index.ets // EntryAbility的Index页面
│ │ └──Second.ets // EntryAbility的Second页面
└──entry/src/main/resources // entry模块的资源文件目录
`HarmonyOS与OpenHarmony鸿蒙文档籽料:mau123789是v直接拿`
entry模块中,EntryAbility内页面的跳转可以通过页面路由router来实现。页面路由router根据页面url找到目标页面,从而实现跳转。效果图如下:
实现UIAbility内页面的跳转,我们首先需要构建两个页面。在“Project”窗口,点击“entry > src > main > ets > pages”,打开“Index.ets”文件,可以看到EntryAbility的Index页面由一个Image组件、两个Text组件、三个Button组件组成。“Index.ets”文件的示例代码如下:
@Entry
@Component
struct Index {
@State text: string = '';
@State bottomMargin: string = StyleConstants.MAIN_INDEX_BUTTON_MARGIN_BOTTOM;
build() {
Column() {
Image($r('app.media.right'))
...
Text($r('app.string.main_index_page_name'))
...
// 条件渲染:当text的值不为空时,显示该组件
if (this.text !== '') {
Text(this.text)
...
}
// 导航到EntryAbility的Second Page
Button($r('app.string.to_main_second_page_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
// 导航到SecondAbility的Index Page
Button($r('app.string.to_second_index_page_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
// 导航到SecondAbility的Second Page
Button($r('app.string.to_second_second_page_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
}
...
}
}
在“Project”窗口,打开“entry > src > main > ets”,右键点击“pages”文件夹,选择“New > Page”,命名为“Second”。可以看到EntryAbility的Second页面由一个Image组件、两个Text组件、一个Button组件组成。“Second.ets”文件的示例代码如下:
@Entry
@Component
struct Second {
...
build() {
Column() {
Image($r('app.media.left'))
...
Text($r('app.string.main_second_page_name'))
...
Text(`${this.src}:${this.count}`)
...
// 返回到EntryAbility的Index Page
Button($r('app.string.back_main_index_page_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
}
...
}
}
从entry模块的Index页面跳转到Second页面,并进行数据传递,通过页面路由router来实现。需要如下几个步骤:
// 导入router模块
import router from '@ohos.router';
// 导航到EntryAbility的Second Page
toEntryAbilitySecond() {
router.pushUrl({
url: 'pages/Second',
params: {
src: textMessage,
count: CommonConstants.NUM_VALUES[0]
}
});
}
@Entry
@Component
struct Second {
...
// 获取Index页面传递过来的自定义参数
params = router?.getParams();
@State src: string = this.params == undefined ? '-' : (this.params as Record< string,Object >)['src'] as string;
@State count: number = this.params == undefined ? 0 : (this.params as Record< string,Object >)['count'] as number;
build() {
Column() {
Image($r('app.media.left'))
...
Text($r('app.string.main_second_page_name'))
...
// 用一个Text文本展示从Index页面传递过来的数据
Text(`${this.src}:${this.count}`)
...
// 返回到EntryAbility的Index Page
Button($r('app.string.back_main_index_page_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
}
...
}
}
从entry模块的Second返回到Index页面,使用router.back来实现。在EntryAbility的Second页面中,点击“返回到EntryAbility的Index Page”按钮后,返回到EntryAbility的Index页面,示例代码如下:
// 返回到EntryAbility的Index Page
router.back();
实现UIAbility间页面的跳转,需要启动另外一个UIAbility,可以通过UIAbilityContext的startAbility的方法来完成。本篇Codelab是用两个模块(entry和device),实现UIAbility间页面的跳转。跳转到指定UIAbility的首页,效果图如下:
@Entry
@Component
struct Index {
...
build() {
Column() {
Image($r('app.media.left'))
...
Text($r('app.string.second_index_page_name'))
...
Text(`${this.src}:${this.count}`)
...
// 停止SecondAbility自身
Button($r('app.string.terminate_second_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
}
...
}
}
首先需要在EntryAbility的“Index.ets”文件中获取UIAbilityContext,示例代码如下:
// 获取UIAbilityContext
let context = getContext(this) as common.UIAbilityContext;
说明: 如果需要使用UIAbilityContext中的方法,需要在对应的页面获取相应的UIAbilityContext。
在EntryAbility的Index页面中,点击“导航到SecondAbility的Index Page”按钮后,调用ButtonClickMethod类中的toSecondAbilityIndex方法,拉起SecondAbility的Index页面。使用UIAbilityContext.startAbility来实现,可以通过parameters来向被拉起方传递参数,示例代码如下:
// 导航到SecondAbility的Index Page
toSecondAbilityIndex(context: common.UIAbilityContext) {
let want: Want = {
'deviceId': '',
'bundleName': CommonConstants.BUNDLE_NAME,
'abilityName': CommonConstants.SECOND_ABILITY_NAME,
'moduleName': CommonConstants.DEVICE_MODULE_NAME,
'parameters': {
src: textMessage,
count: CommonConstants.NUM_VALUES[1]
}
};
context.startAbility(want).then(() = > {
Logger.info(CommonConstants.TAG, `start second ability index page succeed with ${JSON.stringify(want)}`);
}).catch((error: Error) = > {
Logger.error(CommonConstants.TAG, `start second ability index page failedwith ${error}`);
});
}
在SecondAbility的Index页面,获取从EntryAbility的Index页面传递过来的自定义参数,并用一个Text文本展示从Index页面传递过来的数据,示例代码如下:
@Entry
@Component
struct Index {
// 获取从EntryAbility的Index页面传递过来的自定义参数
secondAbilityWant?: Want = GlobalContext.getContext().getObject('secondAbilityWant');
@State src: string = this.secondAbilityWant?.parameters?.src as string ?? '-';
@State count: number = this.secondAbilityWant?.parameters?.count as number ?? 0;
build() {
Column() {
Image($r('app.media.left'))
...
Text($r('app.string.second_index_page_name'))
...
// 用一个Text文本展示从Index页面传递过来的数据
Text(`${this.src}:${this.count}`)
...
// 停止SecondAbility自身
Button($r('app.string.terminate_second_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
}
...
}
}
// 停止SecondAbility自身
terminateSecondAbility(context: common.UIAbilityContext) {
context.terminateSelf().then(() = > {
Logger.info(CommonConstants.TAG, 'terminate second ability self succeed');
}).catch((error: Error) = > {
Logger.error(CommonConstants.TAG, `terminate second ability self failed with ${error}`);
});
}
跳转到指定UIAbility的指定页面(非首页),本章节以从EntryAbility的Index页面跳转到SecondAbility的Second页面为例。只需要在本文档“跳转到指定UIAbility的首页”章节的基础上,另外在device模块中构建一个Second页面。效果图如下:
@Entry
@Component
struct Second {
// 用来接收parameters参数传过来的值
secondAbilityWant?: Want = GlobalContext.getContext().getObject('secondAbilityWant');
@State src: string = this.secondAbilityWant?.parameters?.src as string ?? '-';
@State count: number = this.secondAbilityWant?.parameters?.count as number ?? 0;
build() {
Column() {
Image($r('app.media.left'))
...
Text($r('app.string.second_second_page_name'))
...
Text(`${this.src}:${this.count}`)
...
// 停止SecondAbility自身并返回结果
Button($r('app.string.terminate_second_for_result_btn_text'), { type: ButtonType.Capsule, stateEffect: true })
...
}
...
}
}
// 导航到SecondAbility的Second Page
toSecondAbilitySecond(context: common.UIAbilityContext, callback: (abilityResult: common.AbilityResult) = > void) {
let want: Want = {
'deviceId': '',
'bundleName': CommonConstants.BUNDLE_NAME,
'abilityName': CommonConstants.SECOND_ABILITY_NAME,
'moduleName': CommonConstants.DEVICE_MODULE_NAME,
'parameters': {
url: 'pages/Second',
src: textMessage,
count: CommonConstants.NUM_VALUES[2]
}
};
// 被拉起侧销毁后,在startAbilityForResult回调中可以获取到被拉起侧销毁时传递过来的AbilityResult
context.startAbilityForResult(want).then((result) = > {
callback(result);
Logger.info(CommonConstants.TAG, `start second ability second page succeed with ${JSON.stringify(want)}`);
}).catch((error: Error) = > {
Logger.error(CommonConstants.TAG, `start second ability second page failed with ${error}`);
});
}
onWindowStageCreate(windowStage: Window.WindowStage) {
...
let parameters: Record< string, Object > = (GlobalContext.getContext().getObject('secondAbilityWant') as Want)?.parameters as Record< string, Object >;
let url = parameters?.url ?
parameters.url as string : 'pages/Index';
windowStage.loadContent(url, (err, data) = > {
...
});
}
// 停止SecondAbility自身并返回结果
terminateSecondAbilityForResult(context: common.UIAbilityContext) {
let abilityResult: common.AbilityResult = {
resultCode: CommonConstants.RESULT_CODE,
want: {
'deviceId': '',
'bundleName': CommonConstants.BUNDLE_NAME,
'abilityName': CommonConstants.SECOND_ABILITY_NAME,
'moduleName': CommonConstants.DEVICE_MODULE_NAME,
'parameters': {
src: returnMessage,
count: CommonConstants.RESULT_NUM_VALUE
}
}
};
// 停止SecondAbility自身,并将abilityResult返回给startAbilityForResult接口调用方
context.terminateSelfWithResult(abilityResult).then(() = > {
Logger.info(CommonConstants.TAG, `terminate second ability self with
result succeed with ${JSON.stringify(abilityResult)}`);
}).catch((error: Error) = > {
Logger.error(CommonConstants.TAG, `terminate second ability self with
result failed with ${error}`);
});
}
审核编辑 黄宇
全部0条评论
快来发表一下你的评论吧 !