Search code examples
javaandroidlistpreference

Getting entryValue from ListPreference and set the changes


I don't understand about getting entryValue from the ListPreference. I want to set localization to my app. But the code must be set before setContentView(R.layout.activity_main);. Simply, my app is a multi-language app. What should I do? And how to get an entryValue from ListPreference?

Here is my code:

ListPreference

<ListPreference android:key="pref.language"
            android:title="@string/language"
            android:dialogTitle="@string/select_language"
            android:entries="@array/pref_language_entries"
            android:entryValues="@array/pref_language_values"
            android:defaultValue="en_US"
            android:summary="%s" />

strings.xml

<string-array name="pref_language_entries">
    <item>English</item>
    <item>Indonesian</item>
    <item>Russian</item>
</string-array>

<string-array name="pref_language_values">
    <item>en_US</item>
    <item>in_ID</item>
    <item>ru_RU</item>
</string-array>

As I know, this code is used to change the locale from an activity:

Locale locale = new Locale("entryValue goes here");
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config,
                  getBaseContext().getResources().getDisplayMetrics());

Thanks for your effort...


Solution

  • Why... This is pretty straight forward:

    listPref.getValue() should get you the current selected entry value provided you've actually obtained the reference of the ListPreference from your PreferenceScreen.

    ListPreference documentation link.

    Link to a simple example.