Getting integer or index values from a list prefer

2020-02-10 11:22发布

I'm creating lists in a shared preference and when the onPreferenceChanged() method is called I want to extract the index of the item in the list or an integer value in some cases. I am trying to build the xml data as follows:

in the arrays:

<string-array name="BackgroundChoices">
  <item>Dark Background</item>
  <item>Light Background</item> 
</string-array>
<array name="BackgroundValues">
  <item>1</item>
  <item>0</item> 
</array>
<string-array name="SpeedChoices">
  <item>Slow</item>
  <item>Medium</item>
  <item>Fast</item>
</string-array>    
<array name="SpeedValues">
  <item>1</item>
  <item>4</item>
  <item>16</item>
</array>

in the preferences xml file:

<PreferenceScreen android:key="Settings"  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:title="Settings">

<ListPreference
        android:key="keyBackground"
        android:entries="@array/BackgroundChoices"
        android:summary="Select a light or dark background." 
        android:title="Light or Dark Background"  
        android:positiveButtonText="Okay"   
        android:entryValues="@array/BackgroundValues"/>
<ListPreference 
        android:key="keySpeed" 
        android:entries="@array/SpeedChoices" 
        android:summary="Select animation speed."
        android:title="Speed" android:entryValues="@array/SpeedValues"/>
</PreferenceScreen>

So my xml does not work. I know how to do this using a string-array rather than an array for the values. And I could pull out the value strings and derive what I want from that but I would rather (if possible) be able to have lists where the values were ints, booleans, or enums. What is the customary way to do this?

thanks in advance,

Jay

4条回答
孤傲高冷的网名
2楼-- · 2020-02-10 12:09

Put the preferences in as String and use Integer.parseInt(). I think there is actually a bug report on the limitation you are referring to but I can't find the link. From experience I can tell you to just use Strings and save your self a lot of frustration.

Note to other SO users, if you can prove me wrong, I welcome it.

查看更多
不美不萌又怎样
3楼-- · 2020-02-10 12:09

Here's a ListIntegerPreference class I use (written for com.android.support:preference-v7:24.0.0). It overwrites a few methods and converts between Integer and String where possible, so that the base ListPreference does not recognise, that you are working with Integers instead of Strings.

public class ListIntegerPreference extends ListPreference
{
    public ListIntegerPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
    {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public ListIntegerPreference(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    public ListIntegerPreference(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public ListIntegerPreference(Context context)
    {
        super(context);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue)
    {
        int defValue = defaultValue != null ? Integer.parseInt((String)defaultValue) : 0;
        int value = getValue() == null ? 0 : Integer.parseInt(getValue());
        this.setValue(String.valueOf(restoreValue ? this.getPersistedInt(value) : defValue));
    }

    @Override
    public void setValue(String value)
    {
        try
        {
            Field mValueField = ListPreference.class.getDeclaredField("mValue");
            mValueField.setAccessible(true);
            Field mValueSetField = ListPreference.class.getDeclaredField("mValueSet");
            mValueSetField.setAccessible(true);

            String mValue = (String)mValueField.get(this);
            boolean mValueSet = (boolean)mValueSetField.get(this);

            boolean changed = !TextUtils.equals(mValue, value);
            if(changed || !mValueSet)
            {
                mValueField.set(this, value);
                mValueSetField.set(this, mValueSet);
                this.persistInt(Integer.parseInt(value));
                if(changed) {
                    this.notifyChanged();
                }
            }
        }
        catch (NoSuchFieldException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
    }
}

I'm using this with creating ListPreferences values via code, just try it. It may work right away, or maybe you need to override additional functions. If so, this is a good start and shows you how you can do it...

查看更多
看我几分像从前
4楼-- · 2020-02-10 12:10

Based on the Android's ListPreference, I created IntListPreference. The usage is straighforward - simply put this snippet in your preferences xml:

<org.bogus.android.IntListPreference
    android:key="limitCacheLogs"
    android:defaultValue="20"
    android:entries="@array/pref_download_logs_count_titles"
    android:entryValues="@array/pref_download_logs_count_values"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="@string/pref_download_logs_count" 
/>    

and that in strings.xml

<string name="pref_download_logs_count">Number of logs per cache</string>
<string-array name="pref_download_logs_count_titles">
    <item>10</item>
    <item>20</item>
    <item>50</item>
    <item>Give me all!</item>
</string-array>
<integer-array name="pref_download_logs_count_values">
    <item>10</item>
    <item>20</item>
    <item>50</item>
    <item>-1</item>
</integer-array>
查看更多
▲ chillily
5楼-- · 2020-02-10 12:21

Andrew was correct, the thread is here:

it's still being commented on, and yet no change (as of 2.3.3 anyway).

Integer.parseInt() of .valueOf() will have to work. If valueOf() works without error, use it, as it doesn't allocate as much as parseInt() does, helpful when you NEED to avoid GC like I do.

查看更多
登录 后发表回答