在HarmonyOS中获取设备的屏幕宽度和高度可以通过以下步骤实现:
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.Display;
main.xml
,用于显示屏幕宽度和高度:<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<Text
ohos:id="$+id/screenWidth"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="Screen Width: "
ohos:text_size="50fp"
ohos:layout_alignment="center"/>
<Text
ohos:id="$+id/screenHeight"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="Screen Height: "
ohos:text_size="50fp"
ohos:layout_alignment="center"/>
</DirectionalLayout>
public class MainActivity extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(LayoutScatter.getInstance(this)
.parse(ResourceTable.Layout_main, null, false));
// 获取屏幕宽度和高度
Display display = DisplayManager.getInstance().getDefaultDisplay(this);
int screenWidth = display.getRealSize().width;
int screenHeight = display.getRealSize().height;
// 显示屏幕宽度和高度
Text textScreenWidth = (Text) findComponentById(ResourceTable.Id_screenWidth);
textScreenWidth.setText("Screen Width: " + screenWidth + "px");
Text textScreenHeight = (Text) findComponentById(ResourceTable.Id_screenHeight);
textScreenHeight.setText("Screen Height: " + screenHeight + "px");
}
}
这样,当应用启动时,布局中的Text
组件将显示设备的屏幕宽度和高度。
在HarmonyOS中,可以使用ohos.agp.window.service.Display
类来获取屏幕的实际尺寸。通过getRealSize()
方法可以获取到屏幕的宽度和高度。然后,将获取到的值设置到对应的Text
组件中即可显示在界面上。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云