img

案例介绍

本教程将介绍如何实现新闻阅读应用的动态标签栏。我们将根据新闻分类数据动态生成标签栏,并实现标签的选中状态效果和滚动功能,为用户提供流畅的分类切换体验。

代码实现

// 动态标签页实现
Tabs({ controller: this.tabsController, index: this.currentIndex }) {
  ForEach(this.newsCategories, (category, index) => {
    TabContent() {
      this.NewsList(category.id)
    }
    .tabBar(this.CustomTabBar(category, index))
  })
}
.vertical(false)
.scrollable(true)
.barMode(BarMode.Scrollable)
.barWidth('100%')
.barHeight(48)
.onChange((index: number) => {
  this.currentIndex = index;
})

// 自定义标签栏项目
@Builder
CustomTabBar(category: { id: string, title: string, color: string }, index: number) {
  Text(category.title)
    .fontSize(16)
    .fontWeight(this.currentIndex === index ? FontWeight.Bold : FontWeight.Normal)
    .fontColor(this.currentIndex === index ? category.color : '#666666')
    .height('100%')
    .padding({ left: 16, right: 16 })
    .textAlign(TextAlign.Center)
    .borderRadius(16)
    .backgroundColor(this.currentIndex === index ? this.getAlphaColor(category.color, 0.1) : 'transparent')
}

// 获取带透明度的颜色
getAlphaColor(color: string, alpha: number): string {
  if (color.startsWith('#') && color.length === 7) {
    const r = parseInt(color.slice(1, 3), 16);
    const g = parseInt(color.slice(3, 5), 16);
    const b = parseInt(color.slice(5, 7), 16);
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  }
  return color;
}

代码详解

1. 动态标签页配置

Tabs({ controller: this.tabsController, index: this.currentIndex }) {
  ForEach(this.newsCategories, (category, index) => {
    TabContent() {
      this.NewsList(category.id)
    }
    .tabBar(this.CustomTabBar(category, index))
  })
}

标签页的特点:

  • 使用ForEach动态生成标签页
  • 每个标签页对应一个新闻分类
  • 通过tabBar属性设置自定义标签栏

标签页配置:

  • vertical(false):水平方向的标签页
  • scrollable(true):支持滚动
  • barMode(BarMode.Scrollable):可滚动的标签栏模式
  • barHeight(48):标签栏高度48px

2. 自定义标签栏实现

@Builder
CustomTabBar(category: { id: string, title: string, color: string }, index: number) {
  Text(category.title)
    .fontSize(16)
    .fontWeight(this.currentIndex === index ? FontWeight.Bold : FontWeight.Normal)
    .fontColor(this.currentIndex === index ? category.color : '#666666')
    .backgroundColor(this.currentIndex === index ? this.getAlphaColor(category.color, 0.1) : 'transparent')
}

标签栏样式特点:

  • 使用分类的颜色作为主题色
  • 选中状态使用粗体和主题色
  • 未选中状态使用灰色和常规字重
  • 选中状态添加半透明背景色

3. 选中状态处理

选中状态的样式变化:

  • 字体:Normal → Bold
  • 文本颜色:#666666 → 分类颜色
  • 背景色:透明 → 分类颜色的10%透明度

4. 颜色处理函数

getAlphaColor(color: string, alpha: number): string {
  if (color.startsWith('#') && color.length === 7) {
    const r = parseInt(color.slice(1, 3), 16);
    const g = parseInt(color.slice(3, 5), 16);
    const b = parseInt(color.slice(5, 7), 16);
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  }
  return color;
}

颜色处理功能:

  • 将十六进制颜色转换为RGBA格式
  • 支持设置透明度
  • 用于实现选中状态的背景色效果

总结

通过动态标签栏的实现,我们为新闻阅读应用提供了灵活的分类导航功能。使用ForEach动态生成标签页,通过自定义标签栏实现了独特的选中状态效果,结合可滚动的标签栏模式,为用户提供了流畅的分类切换体验。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐