Get screen width and height in Android

前端 未结 30 4047
野的像风
野的像风 2020-11-22 09:28

How can I get the screen width and height and use this value in:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, \"onM         


        
30条回答
  •  时光取名叫无心
    2020-11-22 10:23

    None of the answers here work correctly for Chrome OS multiple displays, or soon-to-come Foldables.

    When looking for the current configuration, always use the configuration from your current activity in getResources().getConfiguration(). Do not use the configuration from your background activity or the one from the system resource. The background activity does not have a size, and the system's configuration may contain multiple windows with conflicting sizes and orientations, so no usable data can be extracted.

    So the answer is

    val config = context.getResources().getConfiguration()
    val (screenWidthPx, screenHeightPx) = config.screenWidthDp.dp to config.screenHeightDp.dp
    

提交回复
热议问题