Leo Loki
Leo Loki

Reputation: 2575

Why does the language file (locale) not work on a real device?

I made several language files strings.xml(de, en and others). I'm trying to change the locale to display values from the correct language file with help the following code:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setAppLocale("hy")
        val actionBar: androidx.appcompat.app.ActionBar? = supportActionBar
        actionBar?.hide()
        setContentView(R.layout.activity_main)
        .....
    }
    
    fun Context.setAppLocale(language: String): Context {
        val locale = Locale(language)
        Locale.setDefault(locale)
        val config = resources.configuration
        config.setLocale(locale)
        config.setLayoutDirection(locale)
        return createConfigurationContext(config)
    }
    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(ContextWrapper(newBase.setAppLocale("hy")))
    }
    
}

implementation

implementation androidx.appcompat:appcompat:1.4.0'

on emulator, this code works and the text from the desired language file (string-hy) is displayed on the device screen. But on a real device, the required language file is not pulled up, although the check shows that the locale has been changed. I can't figure out what the problem is. And such an problem with different codes for changing languages. Please tell me what could be the problem?

UPD: maybe someone can share working code for changing language to java or kotlin ?

UPD2: code is not working in app in google play only with android app bundle.


Solution: similar questions with multiple solutions: question 1 and question 2

Upvotes: 1

Views: 197

Answers (1)

Mert
Mert

Reputation: 1005

Here is my working code:

    fun setAppLocale(language: String) {
        val locale = Locale(language)
        Locale.setDefault(locale)
        val config = resources.configuration
        config.locale = locale
        activity.resources.updateConfiguration(config, resources.displayMetrics)
    }

Edit: Google splits your app in other languages automatically. But in your case, you wrote your locale strings by yourself. So disable that in your build.gradle(:app) :

android {
    ...
    bundle {
        language {
            enableSplit = false
        }
    }
}

Upvotes: 1

Related Questions