Search code examples
androidandroid-activityandroid-studioandroid-preferences

Using ListPreference in AndroidStudio


I have a settings menu with a list preference from the sample settings activity in Android Studio.

 <ListPreference
    android:key="example_list"
    android:title="@string/pref_title_add_friends_to_messages"
    android:defaultValue="5"
    android:entries="@array/pref_example_list_titles"
    android:entryValues="@array/pref_example_list_values"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null" />

In this list preference you can select 8 different things.

  <string name="pref_title_add_friends_to_messages">Klasse</string>
<string-array name="pref_example_list_titles">
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
</string-array>
<string-array name="pref_example_list_values">
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
</string-array>

I want to use the value of the preference to display links which belong to the 8 different settings.

E.g.:

5 - google.com

6 - wikipedia.com

etc.

As a beginner, how do I get the value of my preference and how do assign the values to the links and put them in one variable, which changes when the preference is being changed?


Solution

  • <string-array name="pref_example_list_values"> will be used as value in the ListPreference. To get the current value, use:

    ListPreference lp = (ListPreference) findPreference("example_list");
    String currentValue = lp.getValue();
    

    To get the value and display it in a text, have a TextView and set the text:

    /* You might create 'if' statement for 8 times because of there are 8 different value in the ListPreference*/
    
    TextView tv = (TextView) findViewById(R.id.textview1);
    
    if (currentValue.equals("5")) {
    // do your thing here, i.e. google.com
    tv.setText("Welcome, 5!");
    }
    if (currentValue.equals("6")) {
    // do your thing here, i.e. wikipedia.com
    tv.setText("Welcome, 6!");
    }