在Scroll组件中使用相对布局无法滚动的问题
参考Scroll组件的文档描述:Scroll
作为可滚动的容器类组件,它最多包含一个子组件,当子组件的布局尺寸在指定的滚动方向上超过Scroll
的视图窗口时,子组件可以滚动。
而RelativeContainer容器的默认高度是根据其父容器的高度来确定的,当前还不支持自适应高度。如果RelativeContainer没有设置具体的高度值,它会自动继承父容器的高度。
这就说明如果Scroll组件的子组件是RelativeContainer,则会违反Scroll组件滚动的条件,于是就无法滚动,如下面代码:
//无法滚动的Scroll
Scroll(){
RelativeContainer(){
Column(){
Text('').width('100%').height('50%').backgroundColor(0xf2ff2)
Text('').width('100%').height('50%').backgroundColor(0x44440)
}
}
}.scrollable(ScrollDirection.Vertical)
.width('100%')
.height('100%')
解决方法
1. 改成弹性布局Flex
Scroll(){
Flex({ direction: FlexDirection.Column }){
Column(){
Text('hello').width('100%').height('50%').backgroundColor(0xf2ff2)
Text('hello').width('100%').height('60%').backgroundColor(0x44440)
}
}
}.width('100%').height('100%')
2. 给RelativeContainer设定大于Scroll的高度
但是考虑到Scroll内组件的高度在开发和运行的时候都可能不固定,以下方法并不好用,只是提供一种让Scroll可以重新滚动的方案,并不适用于真实应用场景。
Scroll(){
RelativeContainer(){
Column(){
Text('hello').width('100%').height('50%').backgroundColor(0xf2ff2)
Text('hello').width('100%').height('60%').backgroundColor(0x44440)
}
}.height('200%')
}.scrollable(ScrollDirection.Vertical)
.width('100%').height('100%')
//OR
Scroll(){
RelativeContainer(){
Column(){
Text('hello').width('100%').height('50%').backgroundColor(0xf2ff2)
Text('hello').width('100%').height('60%').backgroundColor(0x44440)
}
}.height('1000px')
}.scrollable(ScrollDirection.Vertical)
.width('100%').height('500px')