androidkotlinsharedpreferenceslistpreferencepreferencefragment

How to set selected language to whole app using ListPreferences over custom SettingsActivity?


I recently started working with Android App development and know that the similar question has already been asked. But nevertheless, I could not find any solution to solve my problem. I have the following issue: I am using a custom SettingsActivity which includes a SettingsFragment as follows:

SettingsActivity.kt

class SettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        fragmentManager.beginTransaction().add(android.R.id.content, SettingsFragment()).commit()
    }

    class SettingsFragment : PreferenceFragment() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            addPreferencesFromResource(R.xml.settings_pref)
        }
    }
}

In the settings_pref.xml I have a ListPreference as follows:

settings_pref.xml

   <ListPreference
        android:key="list"
        android:title="@string/language"
        android:summary="@string/sel_language"
        android:defaultValue="1"
        android:entries="@array/pref_language_list_titles"
        android:entryValues="@array/pref_language_list_values"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"/>

I tried all the possible solutions I could find on the Google, but could not make it workable. I would like to give the users possibility to choose app language over settings. I need a possible and working solution like Settings -> Language -> Select language -> Return to the MainActivity or even restart the app (if required) and let the user use the app by using a different language within the app regardless of the device system language.

Many thanks in advance and please let me know if I was not enough clear. I will try to give more details if required.


Solution

  • You have to create new string file for new language. (en, fr like that). Then you will have to set android locale in your settings activity. You can store selected language in sharedpreference. You can get answer for set locale. Set Locale programmatically