2

I want set margin for views by programmatically, i should set 50dp for margin_top, i use this code

ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(searchView.getLayoutParams());
                    marginParams.setMargins(0, 75, 0, 0);
                    CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(marginParams);
                    searchView.setLayoutParams(layoutParams);

but in this code set 50px! how can i set this 50dp, not px?!

zzz
  • 41
  • 6
  • Possible duplicate of [In Android, how do I set margins in dp programmatically](http://stackoverflow.com/questions/12728255/in-android-how-do-i-set-margins-in-dp-programmatically) – Harshad Pansuriya Oct 18 '16 at 08:47

6 Answers6

4

You have to convert it:

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);
klijakub
  • 845
  • 11
  • 31
2

For dimens.xml:

context.getResources().getDimensionPixelSize(R.dimen.view_height);

For harcoded value:

int height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
               getContext().getResources().getDisplayMetrics()); 
Barış Söbe
  • 470
  • 4
  • 7
1
public static int dp(int px) {
    return (int) (px * Resources.getSystem().getDisplayMetrics().density);
}
int margin = dp(50);
mstrengis
  • 829
  • 5
  • 15
0

Use this code:

 /**
 * Convert dp to pixel
 *
 * @param dp
 * @return px
 */
public static int dpToPx(final float dp) {
    return Math.round(dp * (Resources.getSystem().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
Simon Schubert
  • 2,010
  • 19
  • 34
0
private int dp2px(int dp) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics());

convert it!

yt.lee
  • 11
  • 1
0

Here's a Kotlin solution

You can use the following function:

fun dpToPx(context: Context, dp: Float): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics).roundToInt()
}

You could choose to take advantage of extensions instead:

// Use: 16f.dpToPx(context)
internal fun Float.dpToPx(context: Context): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, context.resources.displayMetrics).roundToInt()
}

Or if using a dimens resource, use the following:

context.resources.getDimensionPixelSize(R.dimen.some_dimen_id)
James
  • 4,573
  • 29
  • 32