/ Android

Converting dp into pixel Android

I have created an application integrated with ads. I am using banner and interstitial ads. The banner ads generally has a fix height 50dp.
The problem is, if you program the banner to show after the ads loaded, and programmatically set the padding of the other view above or below the ads, that view will consume not exactly 50dp, but 50px or lower (depends on what device).

This problem makes me frustated for several days. So, i finally found the solution. You need to change the height of the banner (in this case 50dp) to pixel.

This code will convert dp to pixel in Kotlin language:

val r = resources
val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50f, r.displayMetrics)

in Java Language:

Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, r.getDisplayMetrics());