本示例主要包含:“登录”、“首页”、“我的”三个页面。
完整示例
HarmonyOS-UI: HarmonyOS一些UI示例 - Gitee.com
软件要求
- DevEco Studio版本:DevEco Studio 3.1 Release。
- HarmonyOS SDK版本:API version 9。
代码结构
- ├──entry/src/main/ets // 代码区
- │ ├──common
- │ │ └──constants
- │ │ └──CommonConstants.ets // 公共常量类
- │ ├──entryability
- │ │ └──EntryAbility.ts // 程序入口类
- │ ├──pages
- │ │ ├──Login.ets // 登录界面
- │ │ └──MainPage.ets // 主界面
- │ ├──view
- │ │ ├──Home.ets // 首页
- │ │ └──Mime.ets // 我的
- │ └──viewmodel
- │ ├──ItemData.ets // 列表数据实体类
- │ └──MainViewModel.ets // 主界面视图Model
- └──entry/src/main/resources // 应用资源目录
实现“登录”页面
页面使用Column容器组件布局,由Image、Text、TextInput、Button、LoadingProgress等基础组件构成。
代码整体结构
@Entry
@Component
struct LoginPage {
...
build() {
Column() {
Image($r('app.media.logo'))
...
Text($r('app.string.login_page'))
...
Text($r('app.string.login_more'))
...
TextInput({ placeholder: $r('app.string.account') })
...
TextInput({ placeholder: $r('app.string.password') })
...
Button($r('app.string.login'), { type: ButtonType.Capsule })
...
if (this.isShowProgress) {
LoadingProgress()
...
}
...
}
...
}
}
获取用户输入
当用户登录前,需要获取用户输入的帐号和密码才能执行登录逻辑。给TextInput设置onChange事件,在onChange事件里面实时获取用户输入的文本信息。
控制LoadingProgress显示和隐藏
给登录按钮绑定onClick事件,调用login方法模拟登录。定义变量isShowProgress结合条件渲染if用来控制LoadingProgress的显示和隐藏。当用户点击按钮时设置isShowProgress为true,即显示LoadingProgress;使用定时器setTimeout设置isShowProgress 2秒后为false,即隐藏LoadingProgress,然后执行跳转到首页的逻辑。
实现页面跳转
页面间的跳转可以使用router模块相关API来实现,使用前需要先导入该模块,然后使用router.replaceUrl()方法实现页面跳转。
login(): void {
...
this.isShowProgress = true;
if (this.timeOutId === -1) {
this.timeOutId = setTimeout(() => {
this.isShowProgress = false;
this.timeOutId = -1;
router.replaceUrl({ url: 'pages/MainPage' });
}, CommonConstants.LOGIN_DELAY_TIME);
}
}
Login完整代码
import prompt from '@system.prompt';
import router from '@ohos.router';
import CommonConstants from '../common/constants/CommonConstants'
@Entry
@Component
struct Login {
@State account: string = '';
@State password: string = '';
@State isShowProgress: boolean = false
private timeOutId: number = -1
@Builder
imageButton(src: Resource) {
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image(src)
}
.height($r('app.float.other_login_image_size'))
.width($r('app.float.other_login_image_size'))
.backgroundColor($r('app.color.background'))
.margin({bottom:$r('app.float.other_login_margin_bottom')})
}
login(): void {
if (this.account === '' || this.password === '') {
prompt.showToast({
message: CommonConstants.INPUT_NOT_EMPTY
})
} else {
this.isShowProgress = true
if