I recently finished developing my android application. I used sp (Scaled pixels) for all textSize. The problem is when i adjusted the system font-size, my application\'s fon
None of the previous answers worked for me, on Android 8.1 (API 27). Here's what worked: Add the following code to your activity:
Kotlin Code:
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(newBase)
val newOverride = Configuration(newBase?.resources?.configuration)
newOverride.fontScale = 1.0f
applyOverrideConfiguration(newOverride)
}
Java Code:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
final Configuration override = new Configuration(newBase.getResources().getConfiguration());
override.fontScale = 1.0f;
applyOverrideConfiguration(override);
}
You don't need to change your AndroidManifest.xml
.
I think use dp
is the best way, but in some case you may want to use a font style, but the style is using sp
, you can convert sp
to dp
by:
fun TextView.getSizeInSp() = textSize / context.resources.displayMetrics.scaleDensity
fun TextView.convertToDpSize() = setTextSize(TypedValue.COMPLEX_UNIT_DIP, getSizeInSp())
so you can use the sp
value from style without dynamic font size, and no need to hardcode the font size