Skip to content

Instantly share code, notes, and snippets.

@titoaesj
Last active June 5, 2024 12:34
Show Gist options
  • Save titoaesj/ccd7ddc3c40350217f2bcae248d2ffc3 to your computer and use it in GitHub Desktop.
Save titoaesj/ccd7ddc3c40350217f2bcae248d2ffc3 to your computer and use it in GitHub Desktop.
Android convert int to dp
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)
@iRYO400
Copy link

iRYO400 commented Aug 1, 2018

Very helpful! Thanks!

@Sunckist
Copy link

Sunckist commented Apr 5, 2019

Great stuff! Thanks!

@muzafakar
Copy link

Great!, Thanks

@ViorelAlbastrelu
Copy link

Helpful! Looks nice. Thanks

@eosobande
Copy link

i was using the context method before, this is way better`

@hamzaahmedkhan
Copy link

Amazing.

@mirkamalg
Copy link

<3

@jisungbin
Copy link

cool! But what does + 0.5f mean?

@titoaesj
Copy link
Author

The adding of 0.5 is used to round UP to the nearest integer value.

@jisungbin
Copy link

The adding of 0.5 is used to round UP to the nearest integer value.

AWESOME!! thanks!!!!

@kingjinho
Copy link

thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment