-
-
Save titoaesj/ccd7ddc3c40350217f2bcae248d2ffc3 to your computer and use it in GitHub Desktop.
Android convert int to dp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OBS: O var_number_int é a varável que recebera o valor a ser convertido em DP | |
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, var_number_int, getResources().getDisplayMetrics()) | |
##KOTLIN | |
val Int.dp: Int | |
get() = (this * Resources.getSystem().displayMetrics.density + 0.5f).toInt() | |
val Float.dp: Int | |
get() = (this * Resources.getSystem().displayMetrics.density + 0.5f).toInt() | |
or | |
val Int.dp: Int | |
get() = (this * Resources.getSystem().displayMetrics.density).roundToInt() | |
val Float.dp: Int | |
get() = (this * Resources.getSystem().displayMetrics.density).roundToInt() | |
Usage then would be cleaner, for example: | |
// before: | |
view.setPadding(ctx.dip(8), ctx.dip(16), ctx.dip(8), ctx.dp(16)) | |
// after: | |
view.setPadding(8.dp, 16.dp, 8.dp, 16.dp) |
Great stuff! Thanks!
Great!, Thanks
Helpful! Looks nice. Thanks
i was using the context method before, this is way better`
Amazing.
<3
cool! But what does + 0.5f
mean?
The adding of 0.5 is used to round UP to the nearest integer value.
The adding of 0.5 is used to round UP to the nearest integer value.
AWESOME!! thanks!!!!
thanks!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very helpful! Thanks!