鸿蒙Harmony arkTS Stage开发 设备横屏竖屏监听事件
具体需求是正常竖屏时候,显示正常的组件,然后有24行,正好显示完全,如果横屏则行数太多显示不全,这时候需要把组件加入到一个Scroll里面,然后设置小行高,满足每一行行高不至于太小。这里MyCustComponent是我自定义页面,有24行Text,横屏时候高度放大2倍,可以在Scroll里面滚动。鸿蒙开发,遇到设备需要根据横屏竖屏不同状态来显示不同界面。
·
鸿蒙开发,遇到设备需要根据横屏竖屏不同状态来显示不同界面。
具体需求是正常竖屏时候,显示正常的组件,然后有24行,正好显示完全,如果横屏则行数太多显示不全,这时候需要把组件加入到一个Scroll里面,然后设置小行高,满足每一行行高不至于太小。
上代码:
@Component
export struct Teletext {
@State fontSizeAdj: number = 0;
@State code:string="700";
scroller:Scroller=new Scroller()
@Prop lTrade:string;
@State bLandscape:boolean=false;
// 当设备横屏时条件成立
listener = mediaquery.matchMediaSync('(orientation: landscape)');
onPortrait(mediaQueryResult) {
if (mediaQueryResult.matches) {
this.bLandscape=true;
} else {
this.bLandscape=false;
}
}
aboutToAppear() {
// 绑定当前应用实例
this.onPortrait = this.onPortrait.bind(this);
// 绑定回调函数
this.listener.on('change', this.onPortrait);
}
// 手动改变设备横竖屏状态函数
private changeOrientation(isLandscape: boolean) {
// 获取UIAbility实例的上下文信息
let context = getContext(this) as common.UIAbilityContext;
// 调用该接口手动改变设备横竖屏状态
window.getLastWindow(context).then((lastWindow) => {
lastWindow.setPreferredOrientation(isLandscape ? window.Orientation.LANDSCAPE : window.Orientation.PORTRAIT)
});
}
build() {
Column() {
Row() {}
.width('100%')
.height('7%')
Row() {
if (this.bLandscape) { // 若设备为横屏状态,更改相应的页面布局
Scroll(this.scroller) {
MyCustComponent().backgroundColor(Color.Grey)
.height('200%')
}
.scrollable(ScrollDirection.Vertical) // 滚动方向纵向
//.scrollBar(BarState.On) // 滚动条常驻显示
.scrollBarColor(Color.Gray) // 滚动条颜色
.scrollBarWidth(10) // 滚动条宽度
.edgeEffect(EdgeEffect.None)
}
else {
MyCustComponent()
.backgroundColor(Color.Grey)
.height('100%')
}
}
.height('100%')
.justifyContent(FlexAlign.Start) //行排列方式
.backgroundColor(Color.White)
}//column
.backgroundColor(Color.Orange)
//}//stack
//.backgroundColor(Color.Green)
}//build
}
这里MyCustComponent是我自定义页面,有24行Text,横屏时候高度放大2倍,可以在Scroll里面滚动。
本文所参考资料:媒体查询(mediaquery)-应用模型概述-应用模型-开发-HarmonyOS应用开发
各种屏幕分辨率相关,屏幕形状相关的查询都能这里找到。
另外一个知识点,Row,Text等组件的行高控制,除了固定height,‘100%’,像素之外,还可以用
.constraintSize({minHeight:25})这样来设置约束。更多推荐


所有评论(0)