Get screen width and height in Android

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

    For kotlin user's

    fun Activity.displayMetrics(): DisplayMetrics {
       val displayMetrics = DisplayMetrics()
       windowManager.defaultDisplay.getMetrics(displayMetrics)
       return displayMetrics
    }
    

    And in Activity you could use it like

         resources.displayMetrics.let { displayMetrics ->
            val height = displayMetrics.heightPixels
            val width = displayMetrics.widthPixels
        }
    

    Or in fragment

        activity?.displayMetrics()?.run {
            val height = heightPixels
            val width = widthPixels
        }
    

提交回复
热议问题