Android應(yīng)用內(nèi)無感知切換語言、修改應(yīng)用字體不隨系統(tǒng)大小改變

1. Utils

    /**
     * 重寫attachBaseContext()-界面加載前,字體大小不隨系統(tǒng)設(shè)置而變化,同時(shí)也更新一下語言
     * lan - zh、en等...
     */
    fun attachBaseContext(context: Context, fontScale: Float = 1f, lan: String): Context {
        val config: Configuration = context.resources.configuration
        config.setLocale(Locale(lan)) // 
        config.fontScale = fontScale
        return context.createConfigurationContext(config)
    }

    /**
     * 重寫getResources()-界面加載前,字體大小不隨系統(tǒng)設(shè)置而變化
     */
    fun getResources(context: Context, resources: Resources, fontScale: Float = 1f): Resources {
        val config: Configuration = resources.configuration
        return if (config.fontScale != fontScale) {
            config.fontScale = fontScale
            context.createConfigurationContext(config).resources
        } else {
            resources
        }
    }

    /**
     * 更新改變(locales、fontScale-setConfiguration)
     */
    private fun setSystemLanguage(context: Context, lan: String) {
        val resources = context.resources
        val config = resources.configuration
        config.setLocale(Locale(lan))
        // 更新資源觸發(fā)attachBaseContext
        resources.updateConfiguration(config, resources.displayMetrics)
    }

    /**
     * 保存字體大小,后通知界面重建,它會(huì)觸發(fā)attachBaseContext
     * 頁面重新構(gòu)建會(huì)白黑屏現(xiàn)象,所以修改語言界面,不執(zhí)行該操作,需要主動(dòng)更新當(dāng)前頁面資源,非棧頂頁面可以調(diào)用
     */
    fun recreate(activity: Activity) {
        Handler(Looper.getMainLooper()).post {
            activity.recreate()
        }
    }

2. 基類 重寫getResources()、attachBaseContext()方法

private var fontScale: Float = 1f
override fun getResources(): Resources {
    return Utils.getResources(this, super.getResources(), fontScale)
}
override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(
        Utils.attachBaseContext(
            newBase ?: applicationContext,
            fontScale
        )
    )
}

3. 切換語言界面,需要主動(dòng)調(diào)用Utils.setSystemLanguage()方法,并更新控件資源

Utils.setSystemLanguage(App.instance)
// 動(dòng)態(tài)刷新當(dāng)前頁面資源
Handler(Looper.getMainLooper()).post{
    App.instance.apply {
        titleView.setText(getString(R.string.language_settings))
        tvChinese.text = getString(R.string.chinese)
        tvEnglish.text = getString(R.string.english)
        btnSubmit.text = getString(R.string.confirm)
    }
}
// 然后通知根頁面重新構(gòu)建 根頁面調(diào)用Utils.recreate()方法
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容