How to assign text size in sp value using java code
http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29
Example:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);
Cleaner and more reusable approach is
define text size in dimens.xml
file inside res/values/
directory:
</resources>
<dimen name="text_medium">14sp</dimen>
</resources>
and then apply it to the TextView
:
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_medium));
You can use a DisplayMetrics
object to help convert between pixels and scaled pixels with the scaledDensity
attribute.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
pixelSize = (int)scaledPixelSize * dm.scaledDensity;