mirror of
https://github.com/dzeiocom/OpenHealth.git
synced 2025-04-24 11:52:15 +00:00
77 lines
2.8 KiB
Kotlin
77 lines
2.8 KiB
Kotlin
package com.dzeio.openhealth.utils
|
|
|
|
import android.app.LocaleManager
|
|
import android.content.Context
|
|
import android.content.res.Configuration
|
|
import android.os.Build
|
|
import android.os.LocaleList
|
|
import androidx.preference.PreferenceManager
|
|
import com.dzeio.openhealth.Settings
|
|
import java.util.Locale
|
|
|
|
|
|
/**
|
|
* Utils object for [Locale]
|
|
*
|
|
* @see https://github.com/gunhansancar/ChangeLanguageExample/blob/master/app/src/main/java/com/gunhansancar/changelanguageexample/helper/LocaleHelper.java
|
|
*/
|
|
object LocaleUtils {
|
|
fun onAttach(context: Context): Context {
|
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
|
val lang = getPersistedData(context)
|
|
return setLanguage(context, lang)
|
|
}
|
|
return context
|
|
}
|
|
|
|
fun getLanguage(context: Context): String {
|
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
return context.getSystemService(LocaleManager::class.java)
|
|
.applicationLocales.get(0).language
|
|
}
|
|
return getPersistedData(context)
|
|
}
|
|
|
|
fun setLanguage(context: Context, language: String): Context {
|
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
context.getSystemService(LocaleManager::class.java)
|
|
.applicationLocales =
|
|
LocaleList.forLanguageTags(language)
|
|
}
|
|
persist(context, language)
|
|
return updateResources(context, language)
|
|
}
|
|
|
|
private fun getPersistedData(context: Context): String {
|
|
// TODO: use the config class
|
|
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
|
|
return preferences.getString(Settings.APP_LANGUAGE, Locale.getDefault().language)
|
|
?: Locale.getDefault().language
|
|
}
|
|
|
|
private fun persist(context: Context, language: String?) {
|
|
// TODO: use the config class
|
|
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
|
|
preferences.edit().putString(Settings.APP_LANGUAGE, language).apply()
|
|
}
|
|
|
|
private fun updateResources(context: Context, language: String): Context {
|
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
|
val locale = Locale(language)
|
|
Locale.setDefault(locale)
|
|
val configuration = context.resources.configuration
|
|
configuration.setLocale(locale)
|
|
configuration.setLayoutDirection(locale)
|
|
return context.createConfigurationContext(configuration)
|
|
}
|
|
val locale = Locale(language)
|
|
Locale.setDefault(locale)
|
|
val resources = context.resources
|
|
val configuration: Configuration = resources.configuration
|
|
configuration.locale = locale
|
|
configuration.setLayoutDirection(locale)
|
|
resources.updateConfiguration(configuration, resources.displayMetrics)
|
|
return context
|
|
}
|
|
}
|