Get screen width and height in Android

前端 未结 30 3679
野的像风
野的像风 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:02

    As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    This code given below is in kotlin and is written accodring to the latest version of Android help you determine width and height:

    fun getWidth(context: Context): Int {
        var width:Int = 0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val displayMetrics = DisplayMetrics()
            val display: Display? = context.getDisplay()
            display!!.getRealMetrics(displayMetrics)
            return displayMetrics.widthPixels
        }else{
            val displayMetrics = DisplayMetrics()
            this.windowManager.defaultDisplay.getMetrics(displayMetrics)
            width = displayMetrics.widthPixels
            return width
        }
    }
    
    fun getHeight(context: Context): Int {
        var height: Int = 0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val displayMetrics = DisplayMetrics()
            val display = context.display
            display!!.getRealMetrics(displayMetrics)
            return displayMetrics.heightPixels
        }else {
            val displayMetrics = DisplayMetrics()
            this.windowManager.defaultDisplay.getMetrics(displayMetrics)
            height = displayMetrics.heightPixels
            return height
        }
    }
    

提交回复
热议问题