文档管理中心
FAQ应用框架开发UI框架UI界面Tabs使用overlay实现在页签栏添加自定义组件

Tabs使用overlay实现在页签栏添加自定义组件

问题现象

Tabs组件如何在TabBar添加页签之外的自定义组件,如文字和图片等?

背景知识

  • Tabs通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图。
  • overlay支持在绑定的组件上方增加类似遮罩的效果,遮罩可以是文本、自定义组件以及ComponentContent。

解决方案

使用浮层overlay可以实现,步骤如下:

  1. 通过Builder设置浮层。值得注意的是:为了避免阻塞对TabBar的操作,需在浮层Builder的最外层组件上配置.hitTestBehavior(HitTestMode.Transparent)。
    收起
    自动换行
    深色代码主题
    复制
    1. @Builder
    2. overlayExample() {
    3. Flex({ justifyContent: FlexAlign.SpaceBetween, direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
    4. Text('登录').fontSize(18).fontColor('#ffcd6c18');
    5. Image($r('app.media.search'))
    6. .width(24)
    7. .height(24);
    8. }
    9. .padding({ left: 20, right: 20 })
    10. .width('100%')
    11. .height(56)
    12. .hitTestBehavior(HitTestMode.Transparent); // 配置浮层不阻塞交互
    13. }
  2. 将浮层添加到Tabs上,注意设置barWidth限制页签大小,腾出浮层容纳的空间,barHeight与浮层的最外层组件高度保持一致。
    收起
    自动换行
    深色代码主题
    复制
    1. Tabs() {
    2. TabContent() {
    3. Column().width('100%').height('100%').backgroundColor(Color.Pink);
    4. }.tabBar(SubTabBarStyle.of('订阅'));
    5. TabContent() {
    6. Column().width('100%').height('100%').backgroundColor(Color.Green);
    7. }.tabBar(SubTabBarStyle.of('推荐'));
    8. TabContent() {
    9. Column().width('100%').height('100%').backgroundColor(Color.Blue);
    10. }.tabBar(SubTabBarStyle.of('热门'));
    11. }
    12. .width('100%')
    13. .height('100%')
    14. .backgroundColor(0xf1f3f5)
    15. .barMode(this.barMode)
    16. .barWidth(200)
    17. .overlay(this.overlayExample(), { align: Alignment.Top });

完整示例参考如下:

收起
自动换行
深色代码主题
复制
  1. @Entry
  2. @Component
  3. struct TabsExample {
  4. text: string = '文本';
  5. barMode: BarMode = BarMode.Fixed;
  6. @Builder
  7. overlayExample() {
  8. Flex({ justifyContent: FlexAlign.SpaceBetween, direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
  9. Text('登录').fontSize(18).fontColor('#ffcd6c18');
  10. Image($r('app.media.search'))
  11. .width(24)
  12. .height(24);
  13. }
  14. .padding({ left: 20, right: 20 })
  15. .width('100%')
  16. .height(56)
  17. .hitTestBehavior(HitTestMode.Transparent); // 配置浮层不阻塞交互
  18. }
  19. build() {
  20. Column() {
  21. Tabs() {
  22. TabContent() {
  23. Column().width('100%').height('100%').backgroundColor(Color.Pink);
  24. }.tabBar(SubTabBarStyle.of('订阅'));
  25. TabContent() {
  26. Column().width('100%').height('100%').backgroundColor(Color.Green);
  27. }.tabBar(SubTabBarStyle.of('推荐'));
  28. TabContent() {
  29. Column().width('100%').height('100%').backgroundColor(Color.Blue);
  30. }.tabBar(SubTabBarStyle.of('热门'));
  31. }
  32. .width('100%')
  33. .height('100%')
  34. .backgroundColor(0xf1f3f5)
  35. .barMode(this.barMode)
  36. .barWidth(200)
  37. .overlay(this.overlayExample(), { align: Alignment.Top });
  38. }
  39. .width('100%')
  40. .height('100%');
  41. }
  42. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词