当页面信息较多时,为了让用户能够聚焦于当前显示的内容,需要对页面内容进行分类,提高页面空间利用率。Tabs组件可以在一个页面内快速实现视图内容的切换,一方面提升查找信息的效率,另一方面精简用户单次获取到的信息量。
知识点:
- Tabs组件的页面组成包含两个部分,分别是TabContent和TabBar。TabContent是内容页,TabBar是导航页签栏,页面结构如下图所示,根据不同的导航类型,布局会有区别,可以分为底部导航、顶部导航、侧边导航,其导航栏分别位于底部、顶部和侧边。
- 底部导航是应用中最常见的一种导航方式。底部导航位于应用一级页面的底部,用户打开应用,能够分清整个应用的功能分类,以及页签对应的内容,并且其位于底部更加方便用户单手操作。底部导航一般作为应用的主导航形式存在,其作用是将用户关心的内容按照功能进行分类,迎合用户使用习惯,方便在不同模块间的内容切换。
- 对于底部导航栏,一般作为应用主页面功能区分,为了更好的用户体验,会组合文字以及对应语义图标表示页签内容,这种情况下,需要自定义导航页签的样式。设置自定义导航栏需要使用tabBar的参数,以其支持的CustomBuilder的方式传入自定义的函数组件样式。例如这里声明tabBuilder的自定义函数组件,传入参数包括页签文字title,对应位置index,以及选中状态和未选中状态的图片资源。通过当前活跃的currentIndex和页签对应的targetIndex匹配与否,决定UI显示的样式。
练习:通过Tabs布局实现首页和内容切换
页面TabsPage
@Entry
@Component
struct TabsPage {
@State currentIndex: number = 0;
build() {
Tabs({ barPosition: BarPosition.End }) {
TabContent() {
Column() {
Text('首页内容')
}
.width('100%')
.height('100%')
.backgroundColor('#0a59f70d')
}
.tabBar(this.tabBuilder('首页', 0, $r('app.media.icon_home_selected'), $r('app.media.icon_home')))
TabContent() {
Column() {
Text('视频列表')
}
.width('100%')
.height('100%')
.backgroundColor('#0a0d47f7')
}
.tabBar(this.tabBuilder('视频', 1, $r('app.media.icon_video_selected'), $r('app.media.icon_video')))
TabContent() {
Column() {
Text('信息列表')
}
.width('100%')
.height('100%')
.backgroundColor('#0a0de3f7')
}
.tabBar(this.tabBuilder('消息', 2, $r('app.media.icon_message_selected'), $r('app.media.icon_message')))
TabContent() {
Column() {
Text('个人内容')
}
.width('100%')
.height('100%')
.backgroundColor('#0a96f70d')
}
.tabBar(this.tabBuilder('个人', 3, $r('app.media.icon_person_selected'), $r('app.media.icon_person')))
}
.width('100%')
.height('100%')
.onChange((index: number) => {
this.currentIndex = index
})
}
@Builder
tabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
Column() {
Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
.size({ width: 25, height: 25 })
Text(title)
.fontColor(this.currentIndex === targetIndex ? '#1698CE' : '#6B6B6B')
}
.width('100%')
.height(50)
.justifyContent(FlexAlign.Center)
}
}