最近因为项目需求,在应用中修改语言并保存用户习惯。后来使用 Kotlin 封装了一下代码,写成框架放到了 JCenter 中,方便依赖使用。
Github地址(含 Demo):MultiLanguage
集成
dependencies {
implementation 'com.cyrus:language:1.0.1'
}
初始化框架
在 Applicaiton 中初始化:
override fun onCreate() {
super.onCreate()
LanguageHelper.init(this)
}
应用配置
覆写 Applicaiton 中的方法:
override fun attachBaseContext(base: Context) {
super.attachBaseContext(LanguageHelper.onAttach(base))
}
覆写 ContextWrapper 子类(如 Activity、Service)中的方法(androidx 版本在 Activity 中需要多调用一次 onAttach(Context)):
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LanguageHelper.onAttach(newBase))
/*
* androidx 方法内部调用的代理方法覆盖了我们设置的属性,所以这里再设置一次。
* 注意:这里传的上下文需要是被覆盖过之后的,所以是 this 不是 newBase。
*/
LanguageHelper.onAttach(this)
}
修改配置
在需要修改配置的地方调用:
LanguageHelper.updateLanguage(context, locale)
或者跟随系统语言:
LanguageHelper.autoLanguage(context)
并根据项目自身需要重启 Activity。
其他 API
/** 设置语言存储实现 */
public fun setLocaleStore(context: Context, store: LanguageStore): Unit
/** 获取系统语言 */
public fun getSystemLanguage(): Locale
/** 获取设置的语言,[defaultLocale]为获取不到时的默认返回 */
public fun getLanguage(context: Context, defaultLocale: Locale? = null): Locale
/** 获取设置语言的资源 */
public fun getResources(context: Context): Resources
/** 获取对应语言的资源 */
public fun getResourcesByLocale(context: Context, locale: Locale): Resources
/** 通过[id]获取设置语言的对应字符串,[formatArgs]用于置换字符串中的占位符 */
public fun getString(context: Context, id: Int, vararg formatArgs: Any): String
/** 通过[id]获取对应语言的对应字符串,[formatArgs]用于置换字符串中的占位符 */
public fun getStringByLocale(context: Context, locale: Locale, id: Int, vararg formatArgs: Any): String