我创建了一些自定义元素,并希望以编程方式将它们放置在右上角(距离上边缘n个像素,距离右边缘m个像素)。因此,我需要获得屏幕宽度和屏幕高度,然后设置位置:
int px = screenWidth - m;
int py = screenHeight - n;
如何在主活动中获取screenWidth和screenHeight?
我创建了一些自定义元素,并希望以编程方式将它们放置在右上角(距离上边缘n个像素,距离右边缘m个像素)。因此,我需要获得屏幕宽度和屏幕高度,然后设置位置:
int px = screenWidth - m;
int py = screenHeight - n;
如何在主活动中获取screenWidth和screenHeight?
当前回答
要获得屏幕尺寸,请使用显示度量
DisplayMetrics displayMetrics = new DisplayMetrics();
if (context != null)
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display defaultDisplay = windowManager.getDefaultDisplay();
defaultDisplay.getRealMetrics(displayMetrics);
}
以像素为单位获取高度和宽度
int width =displayMetrics.widthPixels;
int height =displayMetrics.heightPixels;
其他回答
创建一个类和方法,如下所示:
public MyPoint getScreenDimensionsAsPixel(Context context){
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
return new MyPoint(point.x, point.y);
}
public class MyPoint{
private int width;
private int height;
public MyPoint(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
然后在代码中使用它们:
MyPoint myPoint = getScreenDimensionsAsPixel(MainActivity.this);
Toast.makeText(MainActivity.this, "width: " + String.valueOf(myPoint.getWidth()) + "|" +
"height: " + String.valueOf(myPoint.getHeight()), Toast.LENGTH_LONG).show();
首先加载XML文件,然后编写以下代码:
setContentView(R.layout.main);
Display display = getWindowManager().getDefaultDisplay();
final int width = (display.getWidth());
final int height = (display.getHeight());
根据屏幕分辨率显示宽度和高度。
以上代码已在API级别30中弃用。现在您可以使用以下代码
val width = windowManager.currentWindowMetrics.bounds.width()
val height = windowManager.currentWindowMetrics.bounds.height()
此方法报告包括所有系统栏区域的窗口大小,而Display#getSize(Point)报告不包括导航栏和显示剪切区域的区域。Display#getSize(Point)报告的值可通过以下方式获得:
val metrics = windowManager.currentWindowMetrics
// Gets all excluding insets
val windowInsets = metrics.windowInsets
var insets: Insets = windowInsets.getInsets(WindowInsets.Type.navigationBars())
val cutout = windowInsets.displayCutout
if (cutout != null) {
val cutoutSafeInsets = Insets.of(cutout.safeInsetLeft, cutout.safeInsetTop, cutout.safeInsetRight, cutout.safeInsetBottom)
insets = Insets.max(insets, cutoutSafeInsets)
}
val insetsWidth = insets.right + insets.left
val insetsHeight = insets.top + insets.bottom
// Legacy size that Display#getSize reports
val legacySize = Size(metrics.bounds.width() - insetsWidth, metrics.bounds.height() - insetsHeight)
来源:WindowManager#getCurrentWindowMetrics()
在Kotlin要简单得多。
val displayMetrics = Resources.getSystem().displayMetrics
displayMetrics.heightPixels
displayMetrics.widthPixels
我发现这起了作用。
Rect dim = new Rect();
getWindowVisibleDisplayFrame(dim);