Get screen width and height in Android

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

    Kotlin Version via Extension Property

    If you want to know the size of the screen in pixels as well as dp, using these extension properties really helps:


    DimensionUtils.kt

    import android.content.res.Resources
    import android.graphics.Rect
    import android.graphics.RectF
    import android.util.DisplayMetrics
    import kotlin.math.roundToInt
    
    /**
     * @author aminography
     */
    
    private val displayMetrics: DisplayMetrics by lazy { Resources.getSystem().displayMetrics }
    
    val screenRectPx: Rect
        get() = displayMetrics.run { Rect(0, 0, widthPixels, heightPixels) }
    
    val screenRectDp: RectF
        get() = displayMetrics.run { RectF(0f, 0f, widthPixels.px2dp, heightPixels.px2dp) }
    
    val Number.px2dp: Float
        get() = this.toFloat() / displayMetrics.density
    
    val Number.dp2px: Int
        get() = (this.toFloat() * displayMetrics.density).roundToInt()
    
    

    Usage:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val widthPx = screenRectPx.width()
            val heightPx = screenRectPx.height()
            println("[PX] screen width: $widthPx , height: $heightPx")
    
            val widthDp = screenRectDp.width()
            val heightDp = screenRectDp.height()
            println("[DP] screen width: $widthDp , height: $heightDp")
        }
    }
    

    Result:

    When the device is in portrait orientation:

    [PX] screen width: 1440 , height: 2392
    [DP] screen width: 360.0 , height: 598.0
    

    When the device is in landscape orientation:

    [PX] screen width: 2392 , height: 1440
    [DP] screen width: 598.0 , height: 360.0
    

提交回复
热议问题