HarmonyOS鸿蒙Next中给组件绑定popup弹窗,如何设置在屏幕居中显示
HarmonyOS鸿蒙Next中给组件绑定popup弹窗,如何设置在屏幕居中显示 给组件绑定popup弹窗,如何设置在屏幕居中显示
3 回复
用bindPopup绑定弹窗。想要弹窗居中显示,可以在点击按钮外面套一个column组件,并保证column组件在屏幕中间。参考以下demo:
@Entry
@Component
struct PopupTest1{
@State customPopup: boolean = false
@Builder popupBuilder() {
Row({ space: 2 }) {
Image($r("app.media.app_icon")).width(24).height(24).margin({ left: -5 })
Text('Custom Popup').fontSize(10)
}.width(100).height(50).padding(5)
//.backgroundColor("#4d4d4d")
.justifyContent(FlexAlign.SpaceBetween)
}
build() {
Column(){
Column(){
Button('点击出现弹窗')
.onClick(() => {
this.customPopup = !this.customPopup
})
.bindPopup(this.customPopup, {
builder: this.popupBuilder,
placement: Placement.Bottom,
enableArrow: true,
// popupColor: '#4d4d4d',
popupColor: '#EB4F4D',
showInSubWindow: false,
radius: "8vp",
onStateChange: (e) => {
if (!e.isVisible) {
this.customPopup = false
}
}
})
.alignSelf(ItemAlign.Center)
}
.alignItems(HorizontalAlign.Center).width('100%')
}.backgroundColor(Color.Black)
}
}
更多关于HarmonyOS鸿蒙Next中给组件绑定popup弹窗,如何设置在屏幕居中显示的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,给组件绑定popup弹窗并设置在屏幕居中显示,可以通过以下步骤实现:
-
创建Popup组件:首先,创建一个Popup组件,并设置其布局和内容。
-
设置Popup位置:使用
setPosition方法,将Popup的位置设置为屏幕中心。可以通过获取屏幕的宽度和高度,计算出中心点的坐标。 -
绑定组件事件:在目标组件上绑定事件(如点击事件),当事件触发时,显示Popup弹窗。
示例代码如下:
import { Popup } from '@ohos.arkui.advanced';
import { display } from '@ohos.arkui.base';
// 创建Popup组件
let popup = new Popup();
// 设置Popup内容
popup.setContent(<Text>这是一个居中显示的Popup弹窗</Text>);
// 获取屏幕宽度和高度
let screenWidth = display.getDefaultDisplaySync().width;
let screenHeight = display.getDefaultDisplaySync().height;
// 设置Popup位置为屏幕中心
popup.setPosition(screenWidth / 2, screenHeight / 2);
// 绑定组件事件
targetComponent.onClick(() => {
popup.show();
});
在HarmonyOS鸿蒙Next中,要使Popup弹窗在屏幕居中显示,可以使用Popup组件的setPopupPosition()方法。具体步骤如下:
- 获取屏幕的宽度和高度。
- 计算弹窗的居中位置。
- 使用
setPopupPosition()方法设置弹窗的位置。
示例代码:
Popup popup = new Popup(context);
// 设置弹窗内容
popup.setContent(YourView);
// 获取屏幕尺寸
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;
// 计算居中位置
int popupWidth = YourView.getWidth();
int popupHeight = YourView.getHeight();
int x = (screenWidth - popupWidth) / 2;
int y = (screenHeight - popupHeight) / 2;
// 设置弹窗位置
popup.setPopupPosition(x, y);
popup.show();
通过这种方式,弹窗将居中显示在屏幕上。

