在使用Tabs组件时,常见的高频场景是内容视图的切换。但在实际使用中,可能会遇到以下问题:
问题现象效果图如下:
场景一 | 场景二 | 场景三 | 场景四 |
|---|---|---|---|
|
|
|
|
场景 | 方案 |
|---|---|
场景一 | 关闭点击TabBar页签时切换TabContent的动画,设置animationMode属性入参为AnimationMode.NO_ANIMATION。 |
场景二 | 在onAnimationStart或者onSelected事件中改变控制页签变化的状态变量。 |
场景三 | 设置CustomBuilder中根组件的宽高为100%或者在onTabBarClick事件中执行页签切换逻辑。 |
场景四 | 在onAnimationStart或者onSelected事件中改变控制页签变化的状态变量。 |
@Entry
@Component
struct SceneOneSolution {
private tabsController: TabsController = new TabsController();
build() {
Column() {
Tabs({ controller: this.tabsController }) {
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'));
}
.animationMode(AnimationMode.NO_ANIMATION)
.width('100%')
.height(296);
};
}
}
@Component
struct MyComponent {
private color: string = '';
aboutToAppear(): void {
console.info(`aboutToAppear backgroundColor: ${this.color}`); // 通过打印日志可以观察到没有加载中间页面
}
aboutToDisappear(): void {
console.info(`aboutToDisappear backgroundColor: ${this.color}`);
}
build() {
Column() {
Text(this.color)
.width('90%')
.height(200)
.borderRadius(10)
.backgroundColor('#F1F3F5')
.textAlign(TextAlign.Center)
.fontSize(30);
};
}
} @Entry
@Component
struct SceneThreeSolution2 {
@State currentIndex: number = 0;
tabArr: string[] = ['新闻', '国际', '国内', '个人'];
build() {
Tabs({ index: this.currentIndex }) {
ForEach(this.tabArr, (item: string, index: number) => {
TabContent() {
this.isOnlyShow(item);
}.tabBar(this.tabBuilder(item, index));
}, (item: string) => item);
}
.onTabBarClick((data: number) => {
this.currentIndex = data;
})
.barPosition(BarPosition.End)
.animationDuration(0)
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM]);
}
@Builder
tabBuilder(text: string, index: number): void {
Column() {
Text(text)
.fontSize(20)
.fontWeight(FontWeight.Medium)
.fontColor(this.currentIndex === index ? '#0A59F7' : '#161E26')
.textAlign(TextAlign.Center)
.height(12);
}
.justifyContent(FlexAlign.Start);
}
@Builder
isOnlyShow(text: string): void {
Text(`${text} :仅展示`)
.fontSize(26)
.fontWeight(FontWeight.Bold);
}
} Q:切换至某个TabContent时,如何设置页面中的TextInput默认获焦并拉起软键盘?
A:按以下步骤设置TextInput属性即可。
Q:点击页签切换,无法在onTabBarClick通过return拦截切换,如何解决?
A:可以参考Tabs如何禁止点击切换,以及禁止滑动内容页切换TabContent。
Q:Tabs组件自滚动效果如何实现?
A:定时器setInterval能实现每隔固定时间重复调用一个函数,可以在函数中通过changeIndex控制Tabs切换到指定页签,实现滚动展示的效果。
Q:TabContent切换后onWillShow,onWillHide回调了两次,如何处理?
A:Tabs组件点击页签后即可切换TabContent并触发对应的onWillShow,onWillHide,在onTabBarClick中使用changeIndex方法后使得TabContent跳转了两次,因而触发了两次onWillShow或onWillHide方法。
Q:TabContent左右切换,页签没有跟随滑动。自定义Tabbar如何和TabContent联动?
A:参考自定义页签切换联动和自定义Tabs样式,TabBar底部指示器如何对齐的实现方式。