🌟 使用ArkTS开发鸿蒙应用:底部导航栏的实现
代码解析
1. 导入模块
import { router } from '@kit.ArkUI';
import { httpRequestGet } from '../Utils/HttpUtils';
import { LoginModel, LoginModelUser } from '../model/LoginModel';
import promptAction from '@ohos.promptAction';
import { common } from '@kit.AbilityKit';
import { PositionList } from '../pages/PositionList';
import { MessageList } from '../pages/MessageList';
import { CompanyList } from '../pages/CompanyList';
import My from '../pages/My';
- 导入了多个模块,用于实现路由跳转、HTTP请求、提示框、底部导航栏等功能。
2. 定义主页组件
@Entry
@Component
struct Home {
private backtime: number = 0;
@State message: string = 'Hello World';
@State tabindex: number = 0;
private controller: TabsController = new TabsController();
@State tablist: TableInterface[] = [
{
id: 0,
title: "职位",
icon: $r('app.media.ic_main_tab_company_pre'),
selecticon: $r('app.media.ic_main_tab_company_nor')
},
{
id: 1,
title: "公司",
icon: $r('app.media.ic_main_tab_find_pre'),
selecticon: $r('app.media.ic_main_tab_find_nor')
},
{
id: 2,
title: "消息",
icon: $r('app.media.ic_main_tab_contacts_pre'),
selecticon: $r('app.media.ic_main_tab_contacts_nor')
},
{
id: 3,
title: "我的",
icon: $r('app.media.ic_main_tab_my_pre'),
selecticon: $r('app.media.ic_main_tab_my_nor')
}
];
- 定义了一个名为
Home
的组件。 - 使用
@State
装饰器定义了tabindex
,用于存储当前选中的标签索引。 - 定义了
controller
,用于控制标签的切换。 - 定义了
tablist
,用于存储底部导航栏的标签信息。
3. 标签项构建方法
@Builder
tabBarItem(item: TableInterface) {
Column() {
Image(item.id === this.tabindex ? item.icon : item.selecticon)
.width(25)
.height(25)
.margin({ top: 5 })
Text(item.title)
.fontSize(20)
.fontColor(item.id === this.tabindex ? Color.Green : Color.Black)
.margin({ top: 5 })
}.height(60)
.width("100%")
}
- 定义了一个
tabBarItem
方法,用于构建每个标签项的UI。 - 根据当前选中的标签索引
tabindex
,动态切换图标和文字颜色。
4. 页面布局
build() {
Row() {
Tabs({ index: $$this.tabindex, controller: this.controller }) {
ForEach(this.tablist, (item: TableInterface, index: number) => {
TabContent() {
if (0 === index) {
PositionList();
} else if (1 === index) {
CompanyList();
} else if (2 === index) {
MessageList();
} else if (3 === index) {
My();
}
}.tabBar(this.tabBarItem(item))
})
}.barPosition(BarPosition.End)
.scrollable(false) // 去掉滑动效果
.onChange((index: number) => {
this.tabindex = index;
this.controller.changeIndex(this.tabindex);
})
}.alignItems(VerticalAlign.Center)
.height("100%")
}
- 使用
Row
和Tabs
布局组件,构建主页的UI。 - 使用
ForEach
遍历tablist
,为每个标签项生成对应的TabContent
。 - 根据当前选中的标签索引
tabindex
,动态切换显示的功能页面。 - 使用
onChange
事件监听标签切换,更新tabindex
和controller
的索引。
5. 返回键处理
onBackPress(): boolean | void {
let nowtime = Date.now();
if (nowtime - this.backtime < 1000) {
const mContext = getContext(this) as common.UIAbilityContext;
mContext.terminateSelf();
} else {
this.backtime = nowtime;
promptAction.showToast({
message: "再按一次退出应用"
});
}
return true;
- 定义了
onBackPress
方法,用于处理返回键事件。 - 如果用户在1秒内连续点击返回键两次,则退出应用;否则显示提示信息。
总结
通过上述代码,我们实现了底部导航栏的标签切换和对应的功能页面展示。用户可以通过点击底部导航栏的标签,切换到不同的功能页面。此外,还实现了返回键的防抖处理,提升了用户体验。