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

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

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


当前回答

遵循以下方法:

public static int getWidthScreen(Context context) {
    return getDisplayMetrics(context).widthPixels;
}

public static int getHeightScreen(Context context) {
    return getDisplayMetrics(context).heightPixels;
}

private static DisplayMetrics getDisplayMetrics(Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics;
}

其他回答

DisplayMetrics dm = getResources().getDisplayMetrics();
float fwidth = dm.density * dm.widthPixels;
float fheight = dm.density * dm.heightPixels;

如果getSize由于您的minSDKVersion而给您带来错误,并且您不想使用不推荐的方法(getWidth&getHeight),那么getMetrics解决方案最初是由Balaji.K.于2011年发布的。Nik添加了一条注释,解释getDisplayMetrics也考虑了状态栏大小。

其他一些注释指的是乘以比例(密度),以获得尺寸的精确浮动值。在Android v2.2(API 8)和v4.0中测试,结果良好,无错误/警告。

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

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

这里是Kotlin实现中对上面一些答案的简单改编。它需要清单中如上所述的windowsSoftInput=“adjustResize”:

class KeyboardWatcher(private val layoutRooView: View) {

    companion object {
        private const val MIN_KEYBOARD_HEIGHT = 200f
    }

    private val displayMetrics: DisplayMetrics = layoutRooView.resources.displayMetrics
    private var stateVisible = false

    var observer: ((Boolean) -> Unit)? = null

    init {
        layoutRooView.viewTreeObserver.addOnGlobalLayoutListener {
            val heightDiff = layoutRooView.rootView.height - layoutRooView.height
            if (!stateVisible && heightDiff > dpToPx(MIN_KEYBOARD_HEIGHT)) {
                stateVisible = true
                observer?.invoke(stateVisible)
            } else if(stateVisible) {
                stateVisible = false
                observer?.invoke(stateVisible)
            }
        }
    }

    private fun dpToPx(valueInDp: Float): Float {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, displayMetrics)
    }
}

并使用:

val activityRootView = findViewById<ViewGroup>(R.id.activityRoot)
KeyboardWatcher(activityRootView).observer = { visible ->
    if (visible) do something here ...
}

以下是低于/高于API 30代码的Kotlin扩展函数:

fun Activity.getScreenWidth(): Int {
    return if (Build.VERSION.SDK_INT < 30) {
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        displayMetrics.widthPixels
    } else {
        val metrics = windowManager.currentWindowMetrics
        val insets = metrics.windowInsets
            .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
        metrics.bounds.width() - insets.left - insets.right
    }
}

fun Activity.getScreenHeight(): Int {
    return if (Build.VERSION.SDK_INT < 30) {
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        displayMetrics.heightPixels
    } else {
        val metrics = windowManager.currentWindowMetrics
        val insets = metrics.windowInsets
            .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars())
        metrics.bounds.height() - insets.top - insets.bottom
    }
}

对应的Java助手方法:

public int getScreenWidth(Activity activity) {
    if (Build.VERSION.SDK_INT < 30) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    } else {
        WindowMetrics metrics = activity.getWindowManager().getCurrentWindowMetrics();
        Insets insets = metrics.getWindowInsets()
                .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
        return metrics.getBounds().width() - insets.left - insets.right;
    }
}


public int getScreenHeight(Activity activity) {
    if (Build.VERSION.SDK_INT < 30) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    } else {
        WindowMetrics metrics = activity.getWindowManager().getCurrentWindowMetrics();
        Insets insets = metrics.getWindowInsets()
                .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
        return metrics.getBounds().height() - insets.bottom - insets.top;
    }
}

在“活动”中使用以下代码。

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int wwidth = metrics.widthPixels;