How to change language in kotlin (locale)

后端 未结 1 1967
长情又很酷
长情又很酷 2021-01-19 13:48

I have 2 string files \"en\" and \"tr\". When I change my telephone\'s language string files change automatically(I didn\'t write extra code for this result and I don\'t kno

相关标签:
1条回答
  • 2021-01-19 14:13

    You need to update configuration even before onCreate is called. To do that create a BaseActivity class like this

    open class BaseActivity : AppCompatActivity() {
    
        companion object {
            public var dLocale: Locale? = null
        }
    
        init {
            updateConfig(this)
        }
    
        fun updateConfig(wrapper: ContextThemeWrapper) {
            if(dLocale==Locale("") ) // Do nothing if dLocale is null
                return
    
            Locale.setDefault(dLocale)
            val configuration = Configuration()
            configuration.setLocale(dLocale)
            wrapper.applyOverrideConfiguration(configuration)
        }
    }
    

    Extend you activities from this class.

    Set dLocale in you App class like this:

    class App : Application() {
    
        override fun onCreate() {
            super.onCreate()
    
            var change = ""
            val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
            val language = sharedPreferences.getString("language", "bak")
            if (language == "Turkish") {
                change="tr" 
            } else if (language=="English" ) {
                change = "en"
            }else {
                change ="" 
            } 
    
            BaseActivity.dLocale = Locale(change) //set any locale you want here
        }
    }
    

    You will also need to set App class in your manifest file like this:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">
        //..
    
        <application
            android:name=".App"
            //..>
    
        </application>
    </manifest>    
    

    Note: We should set dLocale only in App onCreate to ensure that all activities have same language.

    0 讨论(0)
提交回复
热议问题