@Entry
@Component
struct Index {// 当前选中的 tab 的索引
@State currentIndex: number = 0;// 生成 tab 的视图函数
@Builder TabBuilder(index: number, text: string, icon: Resource, activeIcon: Resource) {
Column() {
// 根据当前 tab 是否被选中,显示相应的图标和文本
Image(this.currentIndex === index ? activeIcon : icon).width(28)
Text(text).fontSize(10)
.fontColor(this.currentIndex === index ? $r('app.color.black') : '#a0a0a0')
}.width('100%').height('100%').justifyContent(FlexAlign.Center)
}build() {
Column() {
Tabs({
barPosition: BarPosition.End, // Tab 栏位置在底部
index: this.currentIndex // 当前选中的 tab 索引
})
.barMode(BarMode.Fixed) // 固定 Tab 栏模式
.onChange((index: number) => this.currentIndex = index) // Tab 切换时更新选中的索引
.barHeight(50) // 设置 Tab 栏的高度
.scrollable(false) // 禁用 Tab 栏滚动
.width('100%') // Tab 栏宽度
.height('100%') // Tab 栏高度
.backgroundColor($r('app.color.white')) // Tab 栏背景颜色
.vertical(false) // Tab 内容不垂直排列// 定义每个 Tab 内容及其对应的 TabBar
.tabContent(
TabContent() { Home() }
.tabBar(this.TabBuilder(0, '首页', $r('app.media.tabbar_home'), $r('app.media.tabbar_home_active'))),TabContent() { See() }
.tabBar(this.TabBuilder(1, '想看', $r('app.media.tabbar_see'), $r('app.media.tabbar_see_active'))),TabContent() { Service() }
.tabBar(this.TabBuilder(2, '服务', $r('app.media.tabbar_service'), $r('app.media.tabbar_service_active'))),TabContent() { Discover() }
.tabBar(this.TabBuilder(3, '发现', $r('app.media.tabbar_discover'), $r('app.media.tabbar_discover_active'))),TabContent() { My() }
.tabBar(this.TabBuilder(4, '我的', $r('app.media.tabbar_my'), $r('app.media.tabbar_my_active')))
)
}.height('100%') // Column 高度设置为 100%
}
}