Basically I have this inside XML, but I have to recreate it inside a code. How do I do it?
Solved here.
Extract:
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float dp = 20f;
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
Just for completeness: Another solution (which I'd prefer) for the question is given here
setTextSize(float)expects a scaled pixel value. So,setTextSize(10)would give you the desired result. However,getDimension()andgetDimensionPixelSize()return the size in units of pixels.
So for your example it would be
setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.edTxt_text_size));
where <dimen name="edtxt_text_size">10dp</dimen> is set in your dimens.xml file for example.
You can use:
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
Now the value of pixels is equivalent to 10dp at the device's current screen density.
The TypedValue contains other similar methods that help in conversion.