Skip to content

Instantly share code, notes, and snippets.

@trangcongthanh
Forked from titoaesj/.kt
Created May 20, 2020 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trangcongthanh/581f8075985ba3d548488aaa6152c5a0 to your computer and use it in GitHub Desktop.
Save trangcongthanh/581f8075985ba3d548488aaa6152c5a0 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()
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment