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
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:
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()
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")
}
}
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