Добавьте этот флаг в манифест под тегом приложения.
android:supportsRtl="true"
Язык управления классом утилит
object LocaleManagerMew {
val SELECTED_LANGUAGE = "MEW_CURRENT_USER_LANGUAGE"
var mSharedPreference: SharedPreferences? = null
var mEnglishFlag = "en"
var mArabicFlag = "ar"
fun setLocale(context: Context?): Context {
return updateResources(context!!, getCurrentLanguage(context)!!)
}
inline fun setNewLocale(context: Context, language: String) {
persistLanguagePreference(context, language)
updateResources(context, language)
}
inline fun getCurrentLanguage(context: Context?): String? {
var mCurrentLanguage: String?
if (mSharedPreference == null)
mSharedPreference = PreferenceHelper.defaultPrefs(context!!)
mCurrentLanguage = mSharedPreference!![SELECTED_LANGUAGE]
return mCurrentLanguage
}
fun persistLanguagePreference(context: Context, language: String) {
if (mSharedPreference == null)
mSharedPreference = PreferenceHelper.defaultPrefs(context)
mSharedPreference!![SELECTED_LANGUAGE] = language
}
fun updateResources(context: Context, language: String): Context {
var contextFun = context
var locale = Locale(language)
Locale.setDefault(locale)
var resources = context.resources
var configuration = Configuration(resources.configuration)
if (Build.VERSION.SDK_INT >= 17) {
configuration.setLocale(locale)
contextFun = context.createConfigurationContext(configuration)
} else {
configuration.locale = locale
resources.updateConfiguration(configuration, resources.getDisplayMetrics())
}
return contextFun
}
}
Код класса приложения
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
LocaleManagerMew.setLocale(this)
Log.d(MewConstants.mewLogs, "onConfigurationChanged: " + newConfig.locale.getLanguage())
}
Базовое действие
abstract class BaseActivity : AppCompatActivity(){
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(LocaleManagerMew.setLocale(base))
}
}
Смена языка при нажатии кнопки Слушатель в действии
override fun onClick(p0: View?) {
when (p0?.id) {
R.id.switchLanguage -> {
//LocaleManagerMew.setLocale(this@LoginCustomerFragment.activity?.applicationContext)
var mCurrentLanguage = LocaleManagerMew.getCurrentLanguage(this@LoginCustomerFragment.activity?.applicationContext)
if (mCurrentLanguage == LocaleManagerMew.mArabicFlag) {
LocaleManagerMew.setNewLocale(this@LoginCustomerFragment.context!!, LocaleManagerMew.mEnglishFlag)
} else if (mCurrentLanguage == LocaleManagerMew.mEnglishFlag) {
LocaleManagerMew.setNewLocale(this@LoginCustomerFragment.context!!, LocaleManagerMew.mArabicFlag)
}
activity?.recreate()
}
}
}