If I assign an integer value to change a certain text size of a TextView
using java code, the value is interpreted as pixel (px
).
Now does
http://developer.android.com/reference/android/widget/TextView.html#setTextSize%28int,%20float%29
Example:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 65);
This is code for the convert PX to SP format. 100% Works
view.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);
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));
By default setTextSize, without units work in SP (scales pixel)
public void setTextSize (float size)
Added in API level 1
Set the default text size to the given value, interpreted as "scaled pixel" units. This
size is adjusted based on the current density and user font size preference.
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;