获取并设置首选项值

时间:2017-05-11 17:35:43

标签: java android android-preferences

我的目标是管理我的自定义偏好设置。为此,我有以下代码:

MainActivity.java

public class MainActivity extends ActionBarActivity implements View.OnTouchListener, GoogleMap.OnInfoWindowClickListener, LocationListener, GoogleMap.OnMapClickListener{

             public boolean onOptionsItemSelected(MenuItem item) {
                int id = item.getItemId();

                if (id == R.id.action_settings) {
                    launchPreferences(null);
                    return true;
                }

                return super.onOptionsItemSelected(item);
            }
            public void launchPreferences(View view) {
                Intent i = new Intent(this, Preferences.class);
                startActivity(i);
            }
    }

Preferences.java

public class Preferences extends PreferenceActivity {

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        updatePreference();


    }

的settings.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="@+id/preferencias_principal" >
    <EditTextPreference
        android:key="@+id/perimer"
        android:title="Perimeter to list"
        android:summary="Maximum distance to list"
        android:defaultValue="2"/>
    <ListPreference
        android:key="@+id/leguage"
        android:title="Lenguage"
        android:summary="What language would you apply?"
        android:entries="@array/lenguage"
        android:entryValues="@array/lenguageva"
        android:defaultValue="1"/>

</PreferenceScreen>

arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="lenguage">
        <item>English</item>
        <item>Basque</item>
        <item>Spanish</item>
    </string-array>
    <string-array name="lenguageva">
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </string-array>

    <string-array name="number">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
        <item>6</item>
        <item>7</item>
        <item>8</item>
        <item>9</item>
        <item>10</item>
        <item>11</item>
        <item>12</item>
        <item>13</item>
        <item>14</item>
        <item>15</item>
    </string-array>

</resources>

我想使用以下代码获取此首选项的值:

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Integer peri = sharedPref.getInt("@+id/perimer", 1);
Integer leng = sharedPref.getInt("@+id/leguage", 2);

但是这段代码返回默认值, peri = 1和leng = 2

不仅如此,有时偏好活动添加的信息被更改/删除,或者ListPreference项目中没有选择默认项目(如图中所示)。

Interface result

当我使用调试器执行代码here时,这就是结果:

Debugger result

我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:1)

我做过类似的事情,我认为这应该有效。但是这段代码未经测试,可能会引发一些错误。

&#13;
&#13;
public class Preferences extends PreferenceActivity implements android.preference.Preference.OnPreferenceChangeListener {
private ListPreference lang_list;    

@Override protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    // get the stored (or default) value (the index of the selected item)
    Integer leng = sharedPref.getInt("@+id/leguage", 2);

    // get the reference of the ListPreference defined in settings.xml
    lang_list = (ListPreference) getPreferenceManager().findPreference("@+id/leguage");
    // set the selected value
    lang_list.setValueIndex(leng);
    // add a listener to get the changes made by the user. Your Preferences class should implement the OnPreferenceChangeListener interface
    lang_list.setOnPreferenceChangeListener(this);
  }

  ...

  /// When the user selects an item from the list, this function will be fired
  public boolean onPreferenceChange(Preference preference, Object newValue) {
    String key = preference.getKey();
    // ensure that the change has been in the language list
    if (key.equals(lang_list.getKey())) {
      SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
      // set the value for the key "@+id/leguage"
      sharedPref.putInt("@+id/leguage", (int) newValue);
      // save the sharedPref object to the file system
      sharedPref.apply();
      return true;
    }
    return false;
  }
&#13;
&#13;
&#13;

更新2017/06/09:您的Preferences类必须实现android.preference.Preference.OnPreferenceChangeListener接口才能使用行lang_list.setOnPreferenceChangeListener(this);

答案 1 :(得分:1)

主要问题是您用于@+id/perimer@+id/leguage的KEY EditTextPreferenceListPreference

SharedPreferences无法将其识别为首选项KEY。当您添加资源前缀@+id时,它被视为int资源id,这就是为什么它仍然适用于下面的行,但是会出现异常行为并给您错误的输出。

    Integer peri = sharedPref.getInt("@+id/perimer", 1); // WRONG
    Integer leng = sharedPref.getInt("@+id/leguage", 2); // WRONG

<强> SOLUTION:

1。请勿使用优先级为@+id的资源前缀KEY。更新您的settings.xml,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <EditTextPreference
        android:key="perimer"
        android:title="Perimeter to list"
        android:summary="Maximum distance to list"
        android:defaultValue="2"/>
    <ListPreference
        android:key="leguage"
        android:title="Lenguage"
        android:summary="What language would you apply?"
        android:entries="@array/lenguage"
        android:entryValues="@array/lenguageva"
        android:defaultValue="1"/>

</PreferenceScreen>

2。使用SharedPreferences.getString(KEY_NAME, DEFAULT_VALUE)获取偏好值。

    // Get current values
    String peri = mSharedPreferences.getString("perimer", "1");
    String leng = mSharedPreferences.getString("leguage", "2");

3。OnPreferenceChangeListener添加到preferences以获取更新后的values,并根据需要更新偏好summary

    // Required to get the updated value and update summary when you input distance
    mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String peri = value.toString();

            //Update premier summary
            mPreferencePerimer.setSummary(peri);

            return true;
        }
    });

    // Required to get the updated value and update summary when you change language from list
    mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {

            String leng = value.toString();
            int lengIndex = Integer.parseInt(leng) - 1;

            // Update leguage summary
            mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
            return true;
        }
    });

以下是完整代码:

public class Preferences extends PreferenceActivity {

    // Preference Keys
    public static final String KEY_PREF_PERIMER = "perimer";
    public static final String KEY_PREF_LEGUAGE = "leguage";

    // Shared preference
    SharedPreferences mSharedPreferences;

    EditTextPreference mPreferencePerimer;
    ListPreference mPreferenceLeguage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        // Shared preference
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        // Perimer
        mPreferencePerimer = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREF_PERIMER);
        // Leguage
        mPreferenceLeguage = (ListPreference) getPreferenceScreen().findPreference(KEY_PREF_LEGUAGE);

        // Get current values
        String peri = mSharedPreferences.getString(KEY_PREF_PERIMER, "1");
        String leng = mSharedPreferences.getString(KEY_PREF_LEGUAGE, "2");
        int lengIndex = Integer.parseInt(leng) - 1;

        // Set preference summary
        mPreferencePerimer.setSummary(peri);
        mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);

        // Required to get the updated value and update summary when you input distance
        mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {
                String peri = value.toString();

                //Update premier summary
                mPreferencePerimer.setSummary(peri);

                return true;
            }
        });

        // Required to get the updated value and update summary when you change language from list
        mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {

                String leng = value.toString();
                int lengIndex = Integer.parseInt(leng) - 1;

                // Update leguage summary
                mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
                return true;
            }
        });
    }
}

<强>输出:

默认状态

enter image description here

改变后

enter image description here

希望这会有所帮助〜