我创建了一些自定义元素,并希望以编程方式将它们放置在右上角(距离上边缘n个像素,距离右边缘m个像素)。因此,我需要获得屏幕宽度和屏幕高度,然后设置位置:

int px = screenWidth - m;
int py = screenHeight - n;

如何在主活动中获取screenWidth和screenHeight?


当前回答

我会这样包装getSize代码:

@SuppressLint("NewApi")
public static Point getScreenSize(Activity a) {
    Point size = new Point();
    Display d = a.getWindowManager().getDefaultDisplay();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        d.getSize(size);
    } else {
        size.x = d.getWidth();
        size.y = d.getHeight();
    }
    return size;
}

其他回答

科特林牌手表

fun getScreenHeight(activity: Activity): Int {
    val metrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.heightPixels
}

fun getScreenWidth(activity: Activity): Int {
    val metrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.widthPixels
}

JAVA

DisplayMetrics dimension = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dimension);
int w = dimension.widthPixels;
int h = dimension.heightPixels;

只是补充弗朗西斯科的答案。如果你想找出窗口中的位置或屏幕中的位置,另一个更合适的观察者是ViewTreeObserver.OnPreDrawListener()

这也可用于查找在onCreate()时大部分未知的视图的其他属性,例如滚动位置、缩放位置。

此函数以英寸为单位返回近似屏幕大小。

public double getScreenSize()
{
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width=dm.widthPixels;
        int height=dm.heightPixels;
        int dens=dm.densityDpi;
        double wi=(double)width/(double)dens;
        double hi=(double)height/(double)dens;
        double x = Math.pow(wi,2);
        double y = Math.pow(hi,2);
        double screenInches = Math.sqrt(x+y);
        return screenInches;
}

以上代码已在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()

首先加载XML文件,然后编写以下代码:

setContentView(R.layout.main);      
Display display = getWindowManager().getDefaultDisplay();
final int width = (display.getWidth());
final int height = (display.getHeight());

根据屏幕分辨率显示宽度和高度。