Get screen width and height in Android

前端 未结 30 4232
野的像风
野的像风 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条回答
  •  猫巷女王i
    2020-11-22 10:23

    I updated answer for Kotlin language!

    For Kotlin: You should call Window Manager and get metrics. After that easy way.

    val displayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(displayMetrics)
    
    var width = displayMetrics.widthPixels
    var height = displayMetrics.heightPixels
    

    How can we use it effectively in independent activity way with Kotlin language?

    Here, I created a method in general Kotlin class. You can use it in all activities.

    private val T_GET_SCREEN_WIDTH:String = "screen_width"
    private val T_GET_SCREEN_HEIGHT:String = "screen_height"
    
    private fun getDeviceSizes(activity:Activity, whichSize:String):Int{
    
        val displayMetrics = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(displayMetrics)
    
        return when (whichSize){
            T_GET_SCREEN_WIDTH -> displayMetrics.widthPixels
            T_GET_SCREEN_HEIGHT -> displayMetrics.heightPixels
            else -> 0 // Error
        }
    }
    

    Contact: @canerkaseler

提交回复
热议问题