欢迎页面业务
一准备阶段:
业务逻辑先是考虑用户隐私协议,要使用持久化所以考虑使用加载首选项,整体的一个思路是,进入欢迎页面,加载首选项是否同意用户隐私协议,同意就直接进入应用程序,不同意就弹出用户隐私协议的窗口再次询问是否同意,是的话就保存首选项以便再次进入时无需选择直接进入应用程序,不同意就直接退出APP,这就是整体的一个业务逻辑
其中还有用户隐私协议的弹窗,三部分,标题,内容,按钮
这就是全部的准备阶段,然后开始实现代码
二代码实现:
首先写一个自定义弹窗的组件,要在view的目录下建一个UserPrivacyDialog
import { CommonConstants } from '../../common/constants/CommonConstants' @CustomDialog export default struct UserPrivacyDialog { controller: CustomDialogController //先是声明一个成员变量 confirm: () => void//使用两个函数用于处理同意和不同意两种按钮事件 cancel: () => void build() { Column({space: CommonConstants.SPACE_10}){ // 1.标题 Text($r('app.string.user_privacy_title')) .fontSize(20) .fontWeight(CommonConstants.FONT_WEIGHT_700) // 2.内容 Text($r('app.string.user_privacy_content')) // 3.按钮 Button($r('app.string.agree_label')) .width(150) .backgroundColor($r('app.color.primary_color')) .onClick(() => { this.confirm() this.controller.close() }) Button($r('app.string.refuse_label')) .width(150) .backgroundColor($r('app.color.lightest_primary_color')) .fontColor($r('app.color.light_gray')) .onClick(() => { this.cancel() this.controller.close() }) } .width('100%') .padding(10) } }
写完UserPrivacyDialog部分后回到WelcomePage
context = getContext(this) as common.UIAbilityContext controller: CustomDialogController = new CustomDialogController({ builder: UserPrivacyDialog({ }) })
这一部分是将自定义弹窗声明使用
然后是
const PREF_KEY = 'userPrivacyKey'
context = getContext(this) as common.UIAbilityContext controller: CustomDialogController = new CustomDialogController({ builder: UserPrivacyDialog({ confirm: () => this.onConfirm(), cancel: () => this.exitApp() }) })
先是加载首选项,一上来是返回false表示不同意隐私协议弹出窗口,让用户进行选择,同意就调用jumpToIndex()跳转到首页不同意就调用onConfirm()自定义弹窗组件弹窗
async aboutToAppear(){ // 1.加载首选项 let isAgree = await PreferenceUtil.getPreferenceValue(PREF_KEY, false) // 2.判断是否同意 if(isAgree){ // 2.1.同意,跳转首页 this.jumpToIndex() }else{ // 2.2.不同意,弹窗 this.controller.open() } } jumpToIndex(){ setTimeout(() => { router.replaceUrl({ url: 'pages/Index' }) }, 1000) } onConfirm(){ // 1.保存首选项 PreferenceUtil.putPreferenceValue(PREF_KEY, true) // 2.跳转到首页 this.jumpToIndex() } exitApp(){ // 退出APP this.context.terminateSelf() }