目录

Using Tabs (Tabs)

Overview

In daily development, you may often encounter scenarios where the Tabs component is used for navigation, including multi-level nested Tabs, Tabs style customization, Tabs data loading, and dynamically updated Tabs.

When there is a large amount of page information, to enable the user to focus on the currently displayed content, the page content needs to be classified to improve the page space utilization. TheTabs component can quickly switch between views on a page, improving information search efficiency and reducing the amount of information that users receive at a time. To help you gain a more intuitive and comprehensive understanding of the Tabs component, this topic integrates these scenarios into a concrete example of an app home page. It demonstrates various functionalities of the Tabs component and their collaborative effects, as well as interactions with other components or data.

This topic describes the following aspects:

Layout

The page of the Tabs component consists of two parts: TabContent and TabBar. TabContent is the content page, and TabBar is the navigation tab bar. The following figure shows the page structure. The layout varies according to the navigation type. In bottom navigation, top navigation, and side navigation, the navigation tab bar is located at the bottom, top, and edge, respectively.

  • The TabContent component does not support setting of the common width attribute. By default, its width is the same as that of the parent Tabs component.

  • The TabContent component does not support setting of the common height attribute. Its height is determined by the height of the parent Tabs component and the TabBar component.

The Tabs component uses braces to enclose the TabContent component. As shown in the figure, the TabContent component displays the corresponding content page.

Each TabContent component should be mapped to a tab page, which can be configured through the tabBar attribute. The following is an example.

TabContent() {
  // The value in the app.string.homepage_content resource file is "Home tab content."
  Text($r('app.string.homepage_content'))
    .fontSize(30)
}
// The value in the app.string.homepage resource file is "Home."
.tabBar($r('app.string.homepage'))

When setting multiple TabContent components, place them in sequence in the Tabs component.

Tabs() {
  TabContent() {
    // The value in the app.string.homepage_content resource file is "Home tab content."
    Text($r('app.string.homepage_content'))
      .fontSize(30)
  }
  // The value in the app.string.homepage resource file is "Home."
  .tabBar($r('app.string.homepage'))

  TabContent() {
    // The value in the app.string.recommend_content resource file is "Recommended tab content."
    Text($r('app.string.recommend_content'))
      .fontSize(30)
  }
  // The value in the app.string.recommend resource file is "Recommended."
  .tabBar($r('app.string.recommend'))

  TabContent() {
    // The value in the app.string.discover_content resource file is "Discover tab content."
    Text($r('app.string.discover_content'))
      .fontSize(30)
  }
  // The value in the app.string.discover resource file is "Discover."
  .tabBar($r('app.string.discover'))

  TabContent() {
    // The value in the app.string.mine_content resource file is "Me tab content."
    Text($r('app.string.mine_content'))
      .fontSize(30)
  }
  // The value in the app.string.mine resource file is "Me."
  .tabBar($r('app.string.mine'))
}

[h2]Bottom navigation

Bottom navigation is the most common navigation mode in applications. The bottom navigation bar is located at the bottom of the level-1 page of the application. It enables the user to quickly have a picture of the feature categories the moment they open the application. In addition, it facilitates one-hand operations of the user. Bottom navigation generally exists as a main navigation form of an application, in that it provides convenient access to primary destinations anywhere in the application.

Figure 3 Bottom navigation bar

The barPosition attribute of Tabs is used to set the position of the navigation bar. By default, barPosition is set to BarPosition.Start, which means that the navigation bar is located on the top. To display the navigation bar at the bottom, set barPosition to BarPosition.End.

Tabs({ barPosition: BarPosition.End }) {
  // TabContent: Home, Discover, Recommended, and Me
  // ···
}

You can customize the appearance of the bottom navigation bar by setting the BottomTabBarStyle attribute of TabContent. For details, see Example 8: Using Symbol Icons for Bottom Tabs.

[h2]Top Navigation

Top navigation comes in handy when there are many content categories and users need to frequently switch between them. It is usually a further subdivision of the categories in the bottom navigation bar. For example, a theme application may provide a top navigation bar that classifies themes into image, video, and font.

Figure 4 Top navigation bar

Tabs({ barPosition: BarPosition.Start }) {
  // TabContent: Following, Video, Game, Digital, Technology, Sports, Movie
  // ···
}

[h2]Side Navigation

Side navigation is seldom used in applications. It is more applicable to landscape screens. Because the natural eye movement pattern is from left to right, the side navigation bar is located on the left side by default.

Figure 5 Side navigation bar

To implement the side navigation bar, set the vertical attribute of the Tabs component to true. By default, vertical is set to false, indicating that the content page and navigation bar are aligned vertically.

  Tabs({ barPosition: BarPosition.Start }) {
    // TabContent: Home, Discover, Recommended, and Me
    // ···
  }
// ···
  .vertical(true)
  .barWidth(100)
  .barHeight(200)
  • When the vertical attribute is set to false, the tab bar takes up the whole screen width by default. Set barWidth to a proper value.

  • When the vertical attribute is set to true, the tab bar takes up the actual content height by default. Set barHeight to a proper value.

Tabs Layout and Style

In app scenarios involving the Tabs component, you often need to customize the layout and styling of Tabs. This topic introduces several common layout and styling features provided by the Tabs component.

[h2]Tab Alignment

When the number of tabs is insufficient to fill the screen width or height, or when doing so compromises UI aesthetics, the Tabs component provides APIs to customize the alignment of tabs within the navigation bar. For example, in a secondary navigation context with few tabs, left-aligned tab layout may be appropriate.

How to implement

You can set the align parameter of the tabBar by using the barModifier attribute to implement tab alignment. Similar to text alignment, tabs can be aligned to the center, top, bottom, left, or right through customization.

  • These settings only take effect when barMode of the TabBar component is set to BarMode.Scrollable. In addition, you can set a series of common attributes using the barModifier parameter. For details, see TabsOptions.
  • Top and bottom alignment modes are only effective in sidebar navigation. To control the distance between tabs and the top edge in top or bottom navigation bars, use the padding property via barModifier to maintain specific spacing between the tabs and the top of TabBar.

How to develop

Define the tabBarModifier property, use it as a parameter to construct Tabs, and set the alignment mode using tabBarModifier.

@Component
export default struct InTabsComponent {
  // ...
  @State tabBarModifier: CommonModifier = new CommonModifier();
  // ...
  async aboutToAppear() {
    // ...
    this.tabBarModifier.margin({ right: 56 }).align(Alignment.Start);
    // ...
  }
  // ...
  build() {
    // ...
            Tabs({
              // ...
              barModifier: this.tabBarModifier
            }) {
              // ...
            }
            // ...
  }
}

[h2]Tab Style Customization

For bottom navigation bars, typically used to distinguish between functional sections of an app's main page, developers often customize the tab style to enhance the user experience. By using the APIs provided by the Tabs component, you can customize tabs into a combination of icons and text titles, with distinct visual styles for selected and unselected states.

How to implement

The tabBar() method of the Tabs component accepts parameters of the union type. You can pass the UI builder function decorated with @Builder as a parameter to customize the style of the tab bar. Therefore, you can define a UI builder function tabBuilder() and pass it to the tabBar() method as a parameter. Since selected and unselected tabs require different styles, a numeric variable currentIndex, decorated with @State, should be defined. This variable is used within the tabBuilder() function to determine whether a tab is currently selected. When currentIndex changes, it triggers a style update to TabBar. Finally, the onChange function of the Tabs component is registered to update the value of currentIndex in response to tab selection changes.

How to develop

  1. Define the currentIndex property.

    @Component
    export default struct OutTabsComponent {
      @State currentIndex: number = 0;
      // ...
    }
  2. Define the tabBuilder() method decorated with the @Builder decorator for custom style building.

    @Builder
    tabBuilder(index: number, name: string | Resource, icon: Resource) {
      Column() {
    
        SymbolGlyph(icon).fontColor([this.currentIndex === index
          ? $r('app.color.out_tab_bar_font_active_color')
          : $r('app.color.out_tab_bar_font_inactive_color')])
          .fontSize(25)
    
        Text(name)
          .margin({ top: 4 })
          .fontSize(10)
          .fontColor(this.currentIndex === index
            ? $r('app.color.out_tab_bar_font_active_color')
            : $r('app.color.out_tab_bar_font_inactive_color'))
      }
      .justifyContent(FlexAlign.Center)
      .height(Constants.FULL_HEIGHT)
      .width(Constants.FULL_WIDTH)
      .padding({ bottom: 60 })
    }
  3. Pass the tabBuilder() method to Tabs, register the onChange() function with Tabs, and update the currentIndex property within the function.

    Tabs({
      // ...
    }) {
      TabContent() {
        InTabsComponent({ switchNext: this.switchNext })
      }.tabBar(this.tabBuilder(0, $r('app.string.out_bar_text_home'), $r('sys.symbol.house')))
      // ...
    }
    // ...
    .onChange((index: number) => {
      this.currentIndex = index;
    })

[h2]Sticky Tabs

On some secondary navigation pages, content such as banners or other high-priority elements is often placed above the secondary tabs. These elements exit the viewable area when scrolling upward. To provide a better user experience, it is recommended that the navigation bar stick to the top during upward scrolling, allowing users to easily switch between content.

How to implement

You can set the nestedScroll attribute of a scrollable component to control the scrolling order of the parent and child components, thereby achieving the effect of attaching the navigation bar to the top. Specifically, ensure that both TabContent and the upper-level parent component of Tabs are scrollable. Add the nestedScroll attribute to the content component. Set the attribute to enable the parent component to move first when the user swipes up and the content component to move first when the user swipes down, thereby achieving the effect of attaching the navigation bar to the top.

How to develop

Nest the parent component of Tabs inside a Scroll component. The List component within TabContent displays the content. As the List component is inherently scrollable, you only need to configure its nested scrolling behavior.

Scroll() {
  Column() {
    BannerComponent()

    Stack({ alignContent: Alignment.TopEnd }) {
      // ...
      Column() {
        Tabs({
          // ...
        }) {
          ForEach(this.selectTabsViewModel.selectedTabs, (tab: TabItemViewModel, index: number) => {
            if (index === this.selectTabsViewModel.selectedTabs.length - 1) {
              TabContent() {
                List({ space: 10 }) {
                  // ...
                }
                // ...
                .nestedScroll({
                  scrollForward: NestedScrollMode.PARENT_FIRST,
                  scrollBackward: NestedScrollMode.SELF_FIRST
                })
              }
              // ...
            } else {
              // ...
            }
          }, (tab: TabItemViewModel, index: number) => index + '_' + JSON.stringify(tab))
        }
        // ...
      }
      .width(Constants.FULL_WIDTH)
      .height(Constants.FULL_HEIGHT)
      .backgroundColor($r('app.color.out_tab_bar_background_color'))
    }
  }
}

[h2]TabsBar Display Effects

In certain UI design styles, it may be necessary to apply specific visual effects to the tab bar, such as a frosted glass background effect for the home page navigation bar.

When the content exceeds the length of the container, it is typically placed within a scrollable component. In such cases, the tab bar is hidden during upward scrolling and displayed during downward scrolling. In this case, the Tabs component is bound to the scrollable container component through the bindTabsToScrollable or bindTabsToNestedScrollable API. Because the scrolling behavior of TabBar is now bound to and controlled by the scrollable container, any offset or opacity values set manually via the setTabBarOpacity API will not take effect.

Tabs Swiping

The Tabs component offers rich user interaction features, with swipe-based interactions being particularly common. The following section introduces several features related to Tabs and swiping gestures.

[h2]Fixed Navigation Bar

When the content categories are relatively fixed and not scalable, a fixed navigation bar can be used. For example, it can be used for the bottom navigation bar, which generally contains 3 to 5 categories. The fixed navigation bar cannot be scrolled or dragged. The tab bar width is evenly distributed among the categories.

The barMode attribute of the Tabs component is used to determine whether the navigation bar can be scrolled. The default value is BarMode.Fixed.

Tabs({ barPosition: BarPosition.End }) {
  // TabContent: Home, Discover, Recommended, and Me
  // ···
}
.barMode(BarMode.Fixed)

[h2]Swiping Within Two-Layer Nested Tabs

In app development scenarios involving multi-layer nested Tabs components, when both parent and child Tabs components support the swipe-to-switch functionality, you must coordinate their swipe behaviors to avoid conflicts. A common approach is to prioritize swipe gestures for switching child Tabs. Only after the child Tabs have reached their last tab will swiping subsequently trigger tab switching in the parent Tabs.

How to implement

You can use PanGesture in combination with the changeIndex() method of TabsController to switch between double-layer tabs. Specifically, enable swipe-based switching for the child Tabs while disabling it for the parent Tabs; add a PanGesture event handler to the first or last page of the child Tabs to determine the swipe direction; based on the swipe direction, use the changeIndex() method of TabsController to switch to the corresponding tab of the parent Tabs. This ensures that swiping on intermediate tabs of the child Tabs only triggers tab switching within the child Tabs, while swiping on the last tab indirectly triggers tab switching in the parent Tabs via the changeIndex() method.

How to develop

  1. Define the TabsController attribute in the outer Tabs component, and the state attribute variable switchNext and its listener function that are bidirectionally bound to the inner Tabs component. When a tab switch is required, use TabsController to switch to the corresponding tab. Since the outer and inner Tabs in this example are encapsulated into separate custom components, a @Link-decorated variable switchNext is required to serve as the interaction medium between the parent and child components.

    @Component
    export default struct OutTabsComponent {
      // ...
      @State @Watch('onchangeSwitchNext') switchNext: boolean = false;
      // ...
      onchangeSwitchNext() {
        if (this.switchNext) {
          this.switchNext = false;
          this.tabsController.changeIndex(1);
        }
      }
      // ...
      build() {
        Tabs({
          // ...
          controller: this.tabsController,
        }) {
          TabContent() {
            InTabsComponent({ switchNext: this.switchNext })
          }.tabBar(this.tabBuilder(0, $r('app.string.out_bar_text_home'), $r('sys.symbol.house')))
          // ...
        }
        // ...
      }
    }
  2. The inner Tabs component registers a swipe event handler within the last TabContent to listen for left-swiping gestures. When triggered, it modifies the value of the switchNext variable, which is passed to the outer Tabs component to initiate a tab switch.

    @Component
    export default struct InTabsComponent {
      // ...
      @Link switchNext: boolean;
      // ...
      build() {
        // ...
                Tabs({
                  // ...
                }) {
                  ForEach(this.selectTabsViewModel.selectedTabs, (tab: TabItemViewModel, index: number) => {
                    if (index === this.selectTabsViewModel.selectedTabs.length - 1) {
                      TabContent() {
                        // ...
                      }
                      .tabBar(this.tabBuilder(index, tab))
                      .gesture(PanGesture(new PanGestureOptions({ direction: PanDirection.Left })).onActionStart(() => {
                        this.switchNext = true;
                      }))
                      // ...
                    } else {
                      // ...
                    }
                  }, (tab: TabItemViewModel, index: number) => index + '_' + JSON.stringify(tab))
                }
                // ...
      }
    }
  3. Note that swipe-based switching may fail in scenarios using custom transition animations. Therefore, you need to comment out the registration of the transition animation function.

    Tabs({
      barPosition: BarPosition.Start,
      controller: this.subsController,
      barModifier: this.tabBarModifier
    }) {
      // ...
    }
    .customContentTransition(this.customContentTransition)

[h2]Scrollable Tab Bar + More Button

A scrollable tab bar is typically used in top or sidebar navigation. When there are numerous content categories that cannot all be displayed within the screen area, this tab bar allows users to scroll to access hidden tabs.

How to implement

You can set the barMode attribute of the Tabs component to BarMode.Scrollable to implement a scrollable tab bar. To add more buttons, you can use the Stack layout and the barModifier function. Specifically, overlay a More button at the end of the TabBar area of the Tabs component using a stack layout. When tapped, this button can trigger a popup dialog where custom tabs can be displayed.

How to develop

Set the barMode attribute to BarMode.Scrollable and use the Stack layout to add more buttons to the upper right corner of the TabBar.

Stack({ alignContent: Alignment.TopEnd }) {
  Row() {
    Image($r('app.media.more'))
      // ...
      .onClick(() => {
        this.showSelectTabsComponent = !this.showSelectTabsComponent;
      })
  }
  // ...
  .zIndex(1)
  .bindSheet($$this.showSelectTabsComponent, this.sheetBuilder(), {
    detents: [SheetSize.MEDIUM, SheetSize.MEDIUM, 500],
    preferType: SheetType.BOTTOM,
    title: { title: $r('app.string.bind_sheet_title') },
    onWillDismiss: (dismissSheetAction: DismissSheetAction) => {
      this.selectTabsViewModel.updateSelectedTabs();
      if (this.selectTabsViewModel.selectedTabs.length > 0) {
        this.subsController.changeIndex(0);
      }
      dismissSheetAction.dismiss();
    }
  })
  Column() {
    Tabs({
      // ...
    }) {
      // ...
    }
    // ...
    .barMode(BarMode.Scrollable)
    // ...
  }
  .width(Constants.FULL_WIDTH)
  .height(Constants.FULL_HEIGHT)
  .backgroundColor($r('app.color.out_tab_bar_background_color'))
}

[h2]Disabling Swipe-to-Switch for TabContent

By default, the navigation bar supports the swipe-to-switch functionality. However, in cases involving multi-level nested navigation or when other components within the navigation bar require swipe gestures, you can disable the swipe-to-switch feature of the Tabs component to avoid response conflicts. You can disable the function of switching tabs by swiping TabContent by setting the scrollable attribute of the Tabs component to false. Similarly, to disable the edge bounce effect, set edgeEffect to EdgeEffect.None.

Sample code:

build() {
  Tabs({
    // ...
  }) {
    // ...
  }
  // ...
  .scrollable(true)
  // ...
}

Tabs Loading and Updating

During development with the Tabs component, especially when using it as secondary navigation, service requirements often demand finer control over the behavior of the tabs. The following section introduces several scenarios for customizing the tab display logic.

[h2]Displaying Specified Tabs and Preloading

By default, TabContent of a Tabs component loads when the tab is selected for the first time. If the content within TabContent is complex or involves heavy initialization logic, the loading speed may be slow, which can affect the smoothness of tab switching and degrade the user experience. In such cases, preloading the corresponding tab before switching can significantly improve operational fluency.

How to implement

You can use the preloadItem() method of TabController to preload a specified child node. This method accepts an array of indices to be preloaded. If called without parameters, it preloads all specified child nodes at once. For performance reasons, load child nodes in batches. In the sample code, when a certain tab is switched to, the content of the tabs immediately to the left and right of the selected tab are preloaded.

How to develop

Define the subsController attribute and invoke preloadItem() in the onChange function of the Tabs component to preload the tabs on both sides of the current tab.

@Component
export default struct InTabsComponent {
  // ...
  private subsController: TabsController = new TabsController();
  // ...
  build() {
    // ...
            Tabs({
              // ...
              controller: this.subsController,
              // ...
            }) {
              // ...
            }
            // ...
            .onChange((index: number) => {
              this.focusIndex = index;
              this.tabBarItemScroller.scrollToIndex(index, true, ScrollAlign.CENTER);
              let preloadItems: number[] = [];
              if (index - 1 >= 0) {
                preloadItems.push(index - 1);
              }
              if (index + 1 < this.selectTabsViewModel.selectedTabs.length) {
                preloadItems.push(index + 1);
              }
              this.subsController.preloadItems(preloadItems);
            })
            // ...
  }
}

[h2]Switching to a Specified Tab

Non-custom navigation bars follow the default switching logic. If you are using a custom navigation bar, you must manually implement the logic for switching tabs so that when the user switches to a tab, the application displays the corresponding tab page.

From API version 18, the onSelected event method provided by Tabs can be used to listen to the index change and pass the index value of the selected element to selectIndex to implement tab switching.

// To use it as the entry of a page, uncomment @Entry and delete the export keyword.
// @Entry
@Component
export struct ContentPageNoAndTabLinkage {

  @State selectIndex: number = 0;
  @Builder tabBuilder(title: Resource, targetIndex: number) {
    Column() {
      Text(title)
        .fontColor(this.selectIndex === targetIndex ? '#1698CE' : '#6B6B6B')
    }
  }
  build() {
    NavDestination() {
      Column({ space: 12 }) {
        // ...
          Tabs({ barPosition: BarPosition.End }) {
            TabContent() {
              // The value in the app.string.homepage_content resource file is "Home tab content."
              Text($r('app.string.homepage_content')).width('100%').height('100%').backgroundColor('rgb(213,213,213)')
                .fontSize(40).fontColor(Color.Black).textAlign(TextAlign.Center)
            // The value in the app.string.homepage resource file is "Home."
            }.tabBar(this.tabBuilder($r('app.string.homepage'), 0))

            TabContent() {
              // The value in the app.string.discover_content resource file is "Discover tab content."
              Text($r('app.string.discover_content')).width('100%').height('100%').backgroundColor('rgb(112,112,112)')
                .fontSize(40).fontColor(Color.Black).textAlign(TextAlign.Center)
            // The value in the app.string.discover resource file is "Discover."
            }.tabBar(this.tabBuilder($r('app.string.discover'), 1))

            TabContent() {
              // The value in the app.string.recommend_content resource file is "Recommended tab content."
              Text($r('app.string.recommend_content')).width('100%').height('100%').backgroundColor('rgb(39,135,217)')
                .fontSize(40).fontColor(Color.Black).textAlign(TextAlign.Center)
            // The value in the app.string.recommend resource file is "Recommended."
            }.tabBar(this.tabBuilder($r('app.string.recommend'), 2))

            TabContent() {
              // The value in the app.string.mine_content resource file is "Me tab content."
              Text($r('app.string.mine_content')).width('100%').height('100%').backgroundColor('rgb(0,74,175)')
                .fontSize(40).fontColor(Color.Black).textAlign(TextAlign.Center)
            }
            // The value in the app.string.mine resource file is "Me."
            .tabBar(this.tabBuilder($r('app.string.mine'), 3))
          }
          .animationDuration(0)
          .backgroundColor('#F1F3F5')
          .onSelected((index: number) => {
            this.selectIndex = index;
          })
        // ...
      }
      .width('100%')
      // ...
    }
    // ...
  }
}

To enable switching between content pages and tabs without swiping, you can pass currentIndex to the index parameter of Tabs. By changing the value of currentIndex, you can navigate to the content page corresponding to a specific index. Alternatively, use TabsController, which is the controller for the Tabs component, to manage switching of tabs. By using the changeIndex API of TabsController, you can set your application to display the tab content corresponding to the specified index.

// ...
  @State currentIndex: number = 2;
  @State currentAnimationMode: AnimationMode = AnimationMode.CONTENT_FIRST;
  private controller: TabsController = new TabsController();

  // ...
              Tabs({ barPosition: BarPosition.End, index: this.currentIndex, controller: this.controller }) {
                // ...
              }
              .animationDuration(0)
              .height(300)
              .animationMode(this.currentAnimationMode)
              .onChange((index: number) => {
                this.currentIndex = index;
              })

              // The value in the app.string.ContentWillChange_animationMode resource file is "Dynamically Change AnimationMode."
              Button($r('app.string.ContentWillChange_animationMode')).width('50%').margin({ top: 20 })
                .onClick(()=>{
                  if (this.currentAnimationMode === AnimationMode.CONTENT_FIRST) {
                    this.currentAnimationMode = AnimationMode.ACTION_FIRST;
                  } else if (this.currentAnimationMode === AnimationMode.ACTION_FIRST) {
                    this.currentAnimationMode = AnimationMode.NO_ANIMATION;
                  } else if (this.currentAnimationMode === AnimationMode.NO_ANIMATION) {
                    this.currentAnimationMode = AnimationMode.CONTENT_FIRST_WITH_JUMP;
                  } else if (this.currentAnimationMode === AnimationMode.CONTENT_FIRST_WITH_JUMP) {
                    this.currentAnimationMode = AnimationMode.ACTION_FIRST_WITH_JUMP;
                  } else if (this.currentAnimationMode === AnimationMode.ACTION_FIRST_WITH_JUMP) {
                    this.currentAnimationMode = AnimationMode.CONTENT_FIRST;
                  }
                })

              // The value in the app.string.ContentWillChange_changeIndex resource file is "Dynamically Change Index."
              Button($r('app.string.ContentWillChange_changeIndex')).width('50%').margin({ top: 20 })
                .onClick(() => {
                  this.currentIndex = (this.currentIndex + 1) % 4;
                })

              Button('changeIndex').width('50%').margin({ top: 20 })
                .onClick(() => {
                  let index = (this.currentIndex + 1) % 4;
                  this.controller.changeIndex(index);
                })

You can use the onContentWillChange API of the Tabs component to customize the interception callback. The interception callback function is called when a new page is about to be displayed. If the callback returns true, the tab can switch to the new page. If the callback returns false, the tab cannot switch to the new page and will remain on the current page.

Tabs({ barPosition: BarPosition.End, index: this.currentIndex, controller: this.controllerTwo }) {
  // ...
}
// ...
.onContentWillChange((currentIndex, comingIndex) => {
  if (comingIndex === 2) {
    return false;
  }
  return true;
})

[h2]Adding and Deleting Tabs

In daily app development, there is often a need to implement functionality allowing users to customize their channel selection. Typically, these customized channels are displayed through the Tabs component, requiring dynamic updates to the tabs. This example uses a pair of parent and child components to demonstrate this functionality. The parent component is responsible for displaying the tabs and their content, with a More button positioned at the far right of the tab bar. Tapping this button triggers a popup window for users to select the tabs they wish to display. The content of this popup is provided by the child component. After the popup is closed, the tabs in the parent component are updated accordingly.

How to implement

A selectTabsViewModel object is defined, containing an array allTabs representing all selectable tabs and an array selectedTabs representing the selected tabs to be displayed. This object is bound to both the parent component InTabComponent and the child component SelectTabsComponent via @Link. The child component SelectTabsComponent serves as a popup for tab selection. After selection is completed, the popup is closed, and the selectedTabs array in the selectTabsViewModel object is updated, triggering a refresh of the tabs in the parent component InTabComponent.

How to develop

  1. Define the SelectTabsViewModel class, which contains the allTabs property (array of all available tabs), the selectedTabs property (array of tabs to be displayed), and the updateSelectedTabs() method (for updating the array of tabs to be displayed).

    @Observed
    class TabItemArray extends Array<TabItemViewModel> {
    }
    
    @Observed
    export default class SelectTabsViewModel {
      allTabs: TabItemArray = new TabItemArray();
      selectedTabs: TabItemArray = new TabItemArray();
      // ...
    
      async loadTabs(ctx: Context) {
        // ...
      }
    
      updateSelectedTabs() {
        let tempTabs: TabItemViewModel[] = [];
        for (let tab of this.allTabs) {
          if (tab.isChecked) {
            tempTabs.push(tab);
          }
        }
        this.selectedTabs = tempTabs;
      }
    }
  2. Define the selectTabsViewModel property in InTabsComponent and initialize it in the aboutToAppear() method.

    @Component
    export default struct InTabsComponent {
      @State selectTabsViewModel: SelectTabsViewModel = new SelectTabsViewModel();
      // ...
      async aboutToAppear() {
        // ...
    
        await this.selectTabsViewModel.loadTabs(this.ctx);
        // ...
      }
      // ...
    }
  3. Bind the selectTabsViewModel.selectedTabs property to the tabs of Tabs using the ForEach component.

    Tabs({
      // ...
    }) {
      ForEach(this.selectTabsViewModel.selectedTabs, (tab: TabItemViewModel, index: number) => {
        if (index === this.selectTabsViewModel.selectedTabs.length - 1) {
          TabContent() {
            // ...
          }
          .tabBar(this.tabBuilder(index, tab))
          // ...
        } else {
          // ...
        }
      }, (tab: TabItemViewModel, index: number) => index + '_' + JSON.stringify(tab))
    }
  4. Initialize SelectTabsComponent in the popup window triggered by the More button, and pass the selectTabsViewModel property as a two-way bound property. In the popup close event handler, call the selectTabsViewModel.updateSelectedTabs() method to update the components that need to be displayed.

    @Builder
    sheetBuilder() {
      SelectTabsComponent({ selectTabsViewModel: this.selectTabsViewModel })
    }
    build() {
      Scroll() {
        Column() {
          BannerComponent()
    
          Stack({ alignContent: Alignment.TopEnd }) {
            Row() {
              Image($r('app.media.more'))
                // ...
                .onClick(() => {
                  this.showSelectTabsComponent = !this.showSelectTabsComponent;
                })
            }
            // ...
            .zIndex(1)
            .bindSheet($$this.showSelectTabsComponent, this.sheetBuilder(), {
              detents: [SheetSize.MEDIUM, SheetSize.MEDIUM, 500],
              preferType: SheetType.BOTTOM,
              title: { title: $r('app.string.bind_sheet_title') },
              onWillDismiss: (dismissSheetAction: DismissSheetAction) => {
                this.selectTabsViewModel.updateSelectedTabs();
                if (this.selectTabsViewModel.selectedTabs.length > 0) {
                  this.subsController.changeIndex(0);
                }
                dismissSheetAction.dismiss();
              }
            })
            // ...
          }
        }
      }
      // ...
    }
  5. In SelectTabsComponent, dynamically generate a series of toggle components based on the data from the selectTabsViewModel.allTabs array. For each toggle component, register an onChange() event handler. Within this handler, modify the isChecked property of the corresponding tab to reflect its selection state. This updated state is then consumed by the selectTabsViewModel.updateSelectedTabs() method to refresh the collection of displayed tabs.

    @Component
    export default struct SelectTabsComponent {
      @State checkedChange: boolean = false;
      @Link selectTabsViewModel: SelectTabsViewModel;
    
      build() {
        Grid() {
          ForEach(this.selectTabsViewModel.allTabs, (tab: TabItemViewModel) => {
            GridItem() {
              Row() {
                Toggle({ type: ToggleType.Button, isOn: tab.isChecked }) {
                  // ...
                }
                // ...
                .onChange((isOn: boolean) => {
                  tab.isChecked = isOn;
                  this.checkedChange = !this.checkedChange;
                })
              }
            }
          }, (tab: TabItemViewModel, index: number) => index + '_' + JSON.stringify(tab))
        }
        .columnsTemplate(('1fr 1fr 1fr 1fr') as string)
        .height(Constants.FULL_HEIGHT)
      }
    }

[h2]Controlling the Number of Cached Pages

Since API version 19, you can use the cachedMaxCount API to set the maximum number of cached child components and specify the cache mode. By default, all TabContent components are preloaded when the Tabs component is created, and the loaded pages remain in memory, which may cause performance and memory issues. In this case, you can set the cachedMaxCount attribute to control the number of cached pages. After this attribute is set, pages are not preloaded and the lazy loading mechanism is used (pages are loaded only when they are switched to). When a page is switched to, the system determines whether to retain or release the page based on the value of TabsCacheMode.

  • When TabsCacheMode is set to CACHE_BOTH_SIDE, the currently displayed child component and the adjacent components on both sides are cached.

  • When TabsCacheMode is set to CACHE_LATEST_SWITCHED, the currently displayed child component and the most recently switched child component are cached.

  • If a page switching animation is enabled and users switch directly from page 1 to page 3, the animation will include page 2, causing it to be temporarily loaded. If page 2 falls outside the cache range, it will be released immediately after the page switching animation completes.

// To use it as the entry of a page, uncomment @Entry and delete the export keyword.
// @Entry
@Component
export struct NumberOfCachesTabBar {
  build() {
    // ...
          Tabs({ barPosition: BarPosition.Start }) {
            TabContent() {
              MyComponent({ color: '#00CB87' })
            }.tabBar(SubTabBarStyle.of('green'))

            TabContent() {
              MyComponent({ color: '#007DFF' })
            }.tabBar(SubTabBarStyle.of('blue'))

            TabContent() {
              MyComponent({ color: '#FFBF00' })
            }.tabBar(SubTabBarStyle.of('yellow'))

            TabContent() {
              MyComponent({ color: '#E67C92' })
            }.tabBar(SubTabBarStyle.of('pink'))

            TabContent() {
              MyComponent({ color: '#FF0000' })
            }.tabBar(SubTabBarStyle.of('red'))
          }
          .width(360)
          .height(296)
          .backgroundColor('#F1F3F5')
          .cachedMaxCount(2, TabsCacheMode.CACHE_BOTH_SIDE)
          // ...
  }
}

@Component
struct MyComponent {
  private color: string = '';

  aboutToAppear(): void {
    console.info('aboutToAppear backgroundColor:' + this.color);
  }

  aboutToDisappear(): void {
    console.info('aboutToDisappear backgroundColor:' + this.color);
  }

  build() {
    Column()
      .width('100%')
      .height('100%')
      .backgroundColor(this.color)
  }
}

Based on the preceding example code, the caching behavior in different scenarios is as follows:

  1. As shown in the figure, the default page flip animation is used, the CACHE_BOTH_SIDE mode is used, and n is set to 2. When you click the TabBar to switch to the yellow page, TabContent1 to TabContent3 are cached. When you switch to the red page, TabContent1 and TabContent2 are released, and TabContent3 to TabContent5 are cached.

  2. As shown in the figure, the default page switching animation is enabled and the CACHE_LATEST_SWITCHED mode is used with n=2. When users switch to the yellow page using the tab bar, TabContent1 and TabContent3 are cached while TabContent2 is released. Subsequently switching to the red page caches TabContent1, TabContent3, and TabContent5, while releasing TabContent4.

  3. As shown in the figure, the default page switching animation is disabled and the CACHE_BOTH_SIDE mode is used with n=2. When users switch to the yellow page using the tab bar, TabContent1 and TabContent3 are cached. Subsequently switching to the red page caches TabContent3 and TabContent5, while releasing TabContent1.

  4. As shown in the figure, the page flip animation is disabled, the CACHE_LATEST_SWITCHED mode is used, and n is set to 2. When you click the TabBar to switch to the yellow page, TabContent1 and TabContent3 are cached. Subsequently switching to the red page caches TabContent1, TabContent3, and TabContent5.

Tabs Transition Animation

[h2]TabContent Transition Animation

The default tab switching animation for Tabs is a translation animation. If you need to implement more advanced animations, implement custom animations using the APIs provided by Tabs.

How to implement

Use the customContentTransition() function to customize the animation for switching between tab pages. This scenario employs property animation—you can define animatable properties decorated with @State and bind these properties to the corresponding tabs in the build() method. Here, the fade-in and fade-out animation uses the scale and opacity properties of TabContent as the animatable properties. Then, in the customContentTransition() function, set the values of the properties that can be animated in the start frame and end frame of the animation. The system will automatically complete the intermediate frames to generate the animation. For details about property animation, see Implementing Property Animation.

  • When a custom transition animation is used, the default transition animation of the Tabs component will be disabled, and tabs cannot be switched via swipe gestures.
  • Setting customContentTransition to undefined disables the custom transition animation and reverts to the component's default transition animation.
  • Custom transition animations currently do not support interruption mid-playback.
  • At present, custom transition animations are only supported in the following two triggering scenarios: tapping on a tab and calling the TabsController.changeIndex() method.

How to develop

  1. Define the array of properties required for the animation.

    @Component
    export default struct InTabsComponent {
      // ...
      @State scaleList: number[] = [];
      @State opacityList: number[] = [];
      // ...
    }
  2. Bind the property array to the corresponding tab.

    Tabs({
      // ...
    }) {
      ForEach(this.selectTabsViewModel.selectedTabs, (tab: TabItemViewModel, index: number) => {
        if (index === this.selectTabsViewModel.selectedTabs.length - 1) {
          TabContent() {
            // ...
          }
          // ...
          .opacity(this.opacityList[index])
          .scale({
            x: this.scaleList[index], y: this.scaleList[index]
          })
        } else {
          // ...
        }
      }, (tab: TabItemViewModel, index: number) => index + '_' + JSON.stringify(tab))
    }
  3. Define the custom transition function for Tabs.

    @Component
    export default struct InTabsComponent {
      // ...
      @State scaleList: number[] = [];
      @State opacityList: number[] = [];
      // ...
      private animateDuration: number = 1000;
      private animateTimeout: number = 1000;
      private customContentTransition: (from: number, to: number) => TabContentAnimatedTransition =
        (from: number, to: number) => {
          let tabContentAnimatedTransition = {
            timeout: this.animateTimeout,
            transition: (proxy: TabContentTransitionProxy) => {
              this.scaleList[from] = 1.0;
              this.scaleList[to] = 0.5;
              this.opacityList[from] = 1.0;
              this.opacityList[to] = 0.5;
              this.getUIContext().animateTo({
                duration: this.animateDuration,
                onFinish: () => {
                  proxy.finishTransition();
                }
              }, () => {
                this.scaleList[from] = 0.5;
                this.scaleList[to] = 1.0;
                this.opacityList[from] = 0.5;
                this.opacityList[to] = 1.0;
              });
            }
          } as TabContentAnimatedTransition;
          return tabContentAnimatedTransition;
        };
    
      // ...
    }
  4. Pass the transition function as a parameter to the customContentTransition() method of Tabs.

    Tabs({
      barPosition: BarPosition.Start,
      controller: this.subsController,
      barModifier: this.tabBarModifier
    }) {
      // ...
    }
    .customContentTransition(this.customContentTransition)

[h2]Custom Tab Switching Synchronization

In custom tab styles, where the visual appearance differs between selected and unselected states, the tab styling depends on the switching actions of the Tabs component. This requires synchronized behavior between the tabs: during tab switching, the tab style should update automatically.

How to implement

The synchronization effect between the TabBar and TabContent during tab switching can be customized using the onChange event. The specific approach involves defining a @State-decorated variable,** currentIndex**, to identify the index of the currently displayed tab. Then, register a handler function via the onChange() method to update currentIndex, ensuring it remains consistent with the index of the selected tab. In the tab style implementation, the displayed style is determined by comparing currentIndex with each tab's index. Changes to the currentIndex property will automatically trigger updates to the tab styles.

How to develop

Define the currentIndex property and the tabBuilder method, and update the value of currentIndex within the onChange function.

@Component
export default struct OutTabsComponent {
  @State currentIndex: number = 0;
  // ...
  @Builder
  tabBuilder(index: number, name: string | Resource, icon: Resource) {
    Column() {

      SymbolGlyph(icon).fontColor([this.currentIndex === index
        ? $r('app.color.out_tab_bar_font_active_color')
        : $r('app.color.out_tab_bar_font_inactive_color')])
        .fontSize(25)

      Text(name)
        .margin({ top: 4 })
        .fontSize(10)
        .fontColor(this.currentIndex === index
          ? $r('app.color.out_tab_bar_font_active_color')
          : $r('app.color.out_tab_bar_font_inactive_color'))
    }
    // ...
  }
  build() {
    Tabs({
      // ...
    }) {
      // ...
    }
    // ...
    .onChange((index: number) => {
      this.currentIndex = index;
    })
    // ...
  }
}

Supporting Aging-Friendly Design

In aging-friendly scenarios with large font sizes, the bottom tab bar offers a dialog box with large fonts for content display. When the component detects a large font setting, it constructs a long-press dialog box based on the configured text and icons. After the user long-presses the tab bar and then swipes in the dialog box to switch to the next tab, the dialog box updates with content of the new tab. Upon releasing, the dialog box closes and the UI switches to the corresponding tab page.

The dialog is applicable only to the bottom tab page BottomTabBarStyle.

// To use it as the entry of a page, uncomment @Entry and delete the export keyword.
// @Entry
@Component
export struct AgeFriendlyTabs {
 
  build() {
    NavDestination() {
      Column() {
        Tabs({ barPosition: BarPosition.End }) {
          TabContent() {
            Column().width('100%').height('100%').backgroundColor(Color.Pink)
          }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'OverLength'))
 
          TabContent() {
            Column().width('100%').height('100%').backgroundColor(Color.Yellow)
          }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'SixLine'))
 
          TabContent() {
            Column().width('100%').height('100%').backgroundColor(Color.Blue)
          }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Blue'))
 
          TabContent() {
            Column().width('100%').height('100%').backgroundColor(Color.Green)
          }.tabBar(new BottomTabBarStyle($r('sys.media.ohos_app_icon'), 'Green'))
        }
        .vertical(false)
        .scrollable(true)
        .barMode(BarMode.Fixed)
        .width('100%')
        .backgroundColor(0xF1F3F5)
      }.width('80%').height(200)
      .margin({ top: 200 })
    }
  }
}

FAQs

[h2]How Do I Implement Lazy Loading of Pages?

The Tabs component does not support lazy loading natively. To implement the lazy loading effect on a page, you can customize the TabBar and Swiper components and use the LazyForEach to implement lazy loading and release of the page. When using the Tabs component, retain only the TabBar and leave the TabContent section empty. Replace the TabContent with a Swiper component to display the actual content. Define a numeric attribute currentIndex, and use the TabsController, SwiperController, and onchange functions to bind the Tabs and Swiper components to each other. This approach is effective because the Swiper component supports the LazyForEach component, whereas the native Tabs component does not. By using LazyForEach within the Swiper to render content, lazy loading effects equivalent to Tabs can be achieved.

For details, see Implementing Lazy Loading and Resource Release of Pages.

Sample Code