how to prevent system font-size changing effects to android application?

后端 未结 8 2126
执笔经年
执笔经年 2020-11-27 03:49

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

相关标签:
8条回答
  • 2020-11-27 04:23

    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.

    0 讨论(0)
  • 2020-11-27 04:23

    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

    0 讨论(0)
提交回复
热议问题