领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

HarmonyOS NEXT - 页签布局(Tabs)

nixiaole 2025-05-11 17:35:59 知识剖析 26 ℃

当页面信息较多时,为了让用户能够聚焦于当前显示的内容,需要对页面内容进行分类,提高页面空间利用率。Tabs组件可以在一个页面内快速实现视图内容的切换,一方面提升查找信息的效率,另一方面精简用户单次获取到的信息量。

基本布局:

Tabs组件的页面组成包含两个部分,分别是TabContent和TabBar。TabContent是内容页,TabBar是导航页签栏,页面结构如下图所示,根据不同的导航类型,布局会有区别,可以分为底部导航、顶部导航、侧边导航,其导航栏分别位于底部、顶部和侧边。

接口

```typescript

Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: TabsController})

```

通过barPosition参数设置导航栏位置

- BarPosition.Start:顶部,默认

- BarPosition.End:底部

通过vertical属性方法设置侧边栏

代码实例:TabsPage

```typescript

@Entry

@Component

struct TabsPage {

@State message: string = 'TabsPage';

build() {

Column() {

Text(this.message)

.fontSize(30)

.fontWeight(FontWeight.Bold)

Tabs({barPosition:BarPosition.Start}){

TabContent(){

Column(){

Text('首页内容')

}.width('100%').height('100%').backgroundColor(Color.Green)

}.tabBar('首页')

TabContent(){

Column(){

Text('科技资讯')

}.width('100%').height('100%').backgroundColor(Color.Blue)

}.tabBar('科技')

TabContent(){

Column(){

Text('人文信息')

}.width('100%').height('100%').backgroundColor(Color.Orange)

}.tabBar('人文')

TabContent(){

Column(){

Text('秀丽风景')

}.width('100%').height('100%').backgroundColor(Color.Pink)

}.tabBar('风景')

}

// .barWidth('100%')

// .barHeight(60)

.backgroundColor('#EEEEEE')

.vertical(true)

}

.height('100%')

.width('100%')

}

}

```

侧边导航

- 侧边导航是应用较为少见的一种导航模式,更多适用于横屏界面,用于对应用进行导航操作,由于用户的视觉习惯是从左到右,侧边导航栏默认为左侧侧边栏。

- 实现侧边导航栏需要将Tabs的vertical属性设置为true,vertical默认值为false,表明内容页和导航栏垂直方向排列。

```typescript

Tabs({ barPosition: BarPosition.Start }) {

// TabContent的内容:首页、发现、推荐、我的

// ...

}

.vertical(true)

.barWidth(100)

.barHeight(200)

```

说明:

- vertical为false时,tabbar的宽度默认为撑满屏幕的宽度,需要设置barWidth为合适值。

- vertical为true时,tabbar的高度默认为实际内容的高度,需要设置barHeight为合适值。

切换至指定页签

- 在不使用自定义导航栏时,默认的Tabs会实现切换逻辑。在使用了自定义导航栏后,默认的Tabs仅实现滑动内容页和点击页签时内容页的切换逻辑,页签切换逻辑需要自行实现。即用户滑动内容页和点击页签时,页签栏需要同步切换至内容页对应的页签。

- 此时需要使用Tabs提供的onChange事件方法,监听索引index的变化,并将当前活跃的index值传递给currentIndex,实现页签的切换。

```typescript

@Entry

@Component

struct TabsExample1 {

@State currentIndex: number = 2

@Builder tabBuilder(title: string, targetIndex: number) {

Column() {

Text(title)

.fontColor(this.currentIndex === targetIndex ? '#1698CE' : '#6B6B6B')

}

}

build() {

Column() {

Tabs({ barPosition: BarPosition.End }) {

TabContent() {

// ...

}.tabBar(this.tabBuilder('首页', 0))

TabContent() {

// ...

}.tabBar(this.tabBuilder('发现', 1))

TabContent() {

// ...

}.tabBar(this.tabBuilder('推荐', 2))

TabContent() {

// ...

}.tabBar(this.tabBuilder('我的', 3))

}

.animationDuration(0)

.backgroundColor('#F1F3F5')

.onChange((index: number) => {

this.currentIndex = index

})

}.width('100%')

}

}

```

最近发表
标签列表