Conversion between px and dp unit
-
08-06-2021 - |
Question
I want to set layout_marginTop
to 800px using setLayoutParams()
. But I want know what would be this value in dp
unit?
Thanks in advance.
Solution
The logical density of the display is given in the DisplayMetrics
class, and can be retrieved with,
getResources().getDisplayMetrics().density
Thus, to convert dp
to px
, you would do,
int density = getResources().getDisplayMetrics().density;
int px = (int) (dp * density);
To convert px
to dp
, just perform the inverse operation,
int dp = px/density;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow