2

For some odd reason, I could n't get the proper output from the below function, I know I did some silly mistake but not sure though,

public static int convertDpToPixel(int dp, Context context){
       float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,context.getResources().getDisplayMetrics());
        return Math.round(px);
    }

and i am calling the function as - gen_function.convertDpToPixel(R.dimen.button_left_right_margin,this);

The output is a huge number which is not expected, any help much appreciated.

yashkal
  • 713
  • 5
  • 20
Pradeep Kumar
  • 51
  • 1
  • 6
  • 2
    Use `public static float convertDpToPixel(float dp, Context context) { Resources resources = context.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return px; }` – Piyush Feb 09 '18 at 05:25

3 Answers3

7

Use this

int pixels = getResources().getDimensionPixelSize(R.dimen.button_left_right_margin);
Gowthaman M
  • 8,057
  • 8
  • 35
  • 54
Arpan Sarkar
  • 2,301
  • 2
  • 13
  • 24
3

Hope it will help you :-

public static int convertDpIntoPx(Context mContext, float yourdpmeasure) {
    if (mContext == null) {
        return 0;
    }
    Resources r = mContext.getResources();
    int px = (int) TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, yourdpmeasure, r.getDisplayMetrics());
    return px;
}

For more detail

duggu
  • 37,851
  • 12
  • 116
  • 113
2

Hope this will help you.

public static int dpToPx(int dp) {

DisplayMetrics displayMetrics = BaseApplication.appContext.getResources().getDisplayMetrics();
 int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

return px;

 }
Prags
  • 2,457
  • 2
  • 21
  • 38
Chetan Patel
  • 180
  • 8