View.setPadding accepts only in px, is there anyway to setPadding in dp?

AndroidAndroid Layout

Android Problem Overview


Android function View.setPadding(int left, int top, int right, int bottom) only accepts values in px but I want to set padding in dp. Is there any way around it?

Android Solutions


Solution 1 - Android

Straight to code

int padding_in_dp = 6;  // 6 dps
final float scale = getResources().getDisplayMetrics().density;
int padding_in_px = (int) (padding_in_dp * scale + 0.5f);

Solution 2 - Android

If you define the dimension (in dp or whatever) in an XML file (which is better anyway, at least in most cases), you can get the pixel value of it using this code:

context.getResources().getDimensionPixelSize(R.dimen.your_dimension_name)

Solution 3 - Android

There is a better way to convert value to dp programmatically:

int value = 200;
int dpValue = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            value,        
            context.getResources().getDisplayMetrics());

Then apply dpValue to your method, for example: setPadding(dpValue,dpValue,dpValue,dpValue);

Solution 4 - Android

Here's Kotlin version based on accepted answer:

fun dpToPx(dp: Int): Int {
    val scale = resources.displayMetrics.density
    return (dp * scale + 0.5f).toInt()
}

Solution 5 - Android

You can calculate the pixels for a specific DPI value: http://forum.xda-developers.com/showpost.php?p=6284958&postcount=31

Solution 6 - Android

I've the same problem. The only solution i've found (it will not really help you :) ) is to set it in the Xml file.

If you can get the density from the code, you can use the convertion: "The conversion of dip units to screen pixels is simple: pixels = dips * (density / 160)." (from http://developer.android.com/guide/practices/screens_support.html )

Edit: you can get the screen density: http://developer.android.com/reference/android/util/DisplayMetrics.html#densityDpi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSharjeelView Question on Stackoverflow
Solution 1 - AndroidLabeeb PanampullanView Answer on Stackoverflow
Solution 2 - AndroidMichael SparmannView Answer on Stackoverflow
Solution 3 - AndroidwapnView Answer on Stackoverflow
Solution 4 - AndroidJiyehView Answer on Stackoverflow
Solution 5 - AndroidMossView Answer on Stackoverflow
Solution 6 - AndroidKhetzalView Answer on Stackoverflow