前言
上一讲我们讲到了页面跳转,更加详细复杂复杂的页面跳转、弹窗、参数传递更新等在后续具体用到时再进行实现和讲解。接下来的几讲我们将开始实现一些常见的页面布局,本讲的内容是使用Stack容器叠加固定区域与滑动区域,我们以一个闹钟的主界面为例来看看这种布局是怎么实现的。
一、Stack容器几个主要特点
1、子组件按声明顺序依次叠加,后添加的组件覆盖在先添加的组件上方,类似图层堆叠效果。
也可以通过 zIndex
属性可手动调整组件显示层级,数值越大越靠前。
2、通过 alignContent
参数设置子组件整体对齐方式(默认 Alignment.Center
)。
3、支持子组件通过 position
+ markAnchor
实现独立精确定位。
4、结合 Scroll
容器实现可滚动内容+固定操作按钮共存。
二、通过Stack实现闹钟主界面布局
1、先看看实现的效果,再一步步展示相关的代码实现
2、在pages下新建uilayout目录
2、在uilayout目录下新建页面UILayout.ets和FixedLayout.ets
页面关键代码如下:
UILayout.ets
Row() {
Column() {
Button(FIXEDLAYOUT)
.onClick(() => {
try {
router.pushUrl({ // 压入页面栈,可通过router.back()返回原页
url: 'pages/uilayout/FixedLayout',
params: new RouterParam('Open new page by pushUrl') // 传递到新页面的参数,如果不需要传递参数,这个字段可以不需要
});
} catch (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`pushUrl failed, code is ${code}, message is ${message}`);
}
})
}
}
FixedLayout.ets
onPageShow() {
window.getLastWindow(getContext(this), (err, data) => {
if (!err.code) {
data.setWindowLayoutFullScreen(true); // 强制全屏显示,消除系统安全区域导致的上下白边,确保布局覆盖全屏区域
}
});
}
build() {
/*
使用Stack容器叠加固定区域与滑动区域
*/
Stack() {
// 顶部标题栏
Row() {
Text('闹钟')
.margin({ top: '10%'})
.fontWeight(FontWeight.Bold)
.height('100%')
.width('100%')
.textAlign(TextAlign.Center);
}
.backgroundColor(themeBackupColor)
.position({ x: 0, y: 0 })
.height('10%')
.width('100%');
// 中间滑动区域
Scroll() {
Column() {
ForEach(this.dataList, (item: string) => {
Row() {
Text(item)
//.height(100)
//.width('100%')
.margin({left:10})
//.backgroundColor(Color.White);
}
.borderRadius(16)
.height(100)
.width('100%')
.margin({top:8, bottom:8})
.backgroundColor(Color.White);
})
}
.margin({left:16, right:16})
}
.height('83%')
.width('100%')
.backgroundColor(themeBackupColor)
.position({ x: 0, y: '10%' });
//.margin({ top: 10, bottom: 10 });
// 底部导航栏
Row() {
Text('闹钟页')
//.backgroundColor(Color.Brown)
//.fontColor(Color.Green)
.textAlign(TextAlign.Center)
.height('100%')
.width('50%');
Text('我的页')
//.backgroundColor(Color.Brown)
//.fontColor(Color.Green)
.textAlign(TextAlign.Center)
.height('100%')
.width('50%');
}
.backgroundColor(themeBackupColor)
.width('100%')
.height('7%')
.position({ x: 0, y: '93%' });
// 底部导航栏
Button('+')
.width(50)
.height(50)
.borderRadius(25)
.fontSize(30)
.fontColor(Color.Black)
.backgroundColor(themeBackupColor)
.position({x: '50%', y: '90%' })
.markAnchor({ x: '50%', y: '90%' })
.alignSelf(ItemAlign.Center)
.zIndex(999);
}
.width('100%')
.height('100%')
.expandSafeArea([SafeAreaType.SYSTEM]); // 扩展至系统安全区域
}
3、在Index.ets中添加入口代码
Button(UILAYOUT)
.onClick(() => {
router.pushUrl({
url: 'pages/uilayout/UILayout'
});
})
4、编译运行看效果吧
页面代码文件见附件:使用Stack容器叠加固定区域与滑动区域实现闹铃主界面