1

我是 android 新手,目前在使用 Preferences 时,我有以下疑问,API 说明如下: http://developer.android.com/reference/android/content/SharedPreferences.html 对首选项的修改必须通过 SharedPreferences .Editor 对象以确保首选项值保持一致状态

但在另一个链接中,遵循以下代码样式:


public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(KEY_PREF_SYNC_CONN)) {           
        Preference connectionPref = findPreference(key);        
        connectionPref.setSummary(sharedPreferences.getString(key, ""));    
    }
}

那么在不使用编辑和提交的情况下编辑 Preference obj 是否可以?

编辑

编辑代码

问题是我无法在摘要中设置默认值这是我用来解决此问题的完整代码....

public class Settings extends PreferenceActivity implements
                OnSharedPreferenceChangeListener {      
    //initializations      
    protected void onCreate(Bundle savedInstanceState) {
     bla bla
    PreferenceManager.setDefaultValues(getBaseContext(), R.xml.preferences, false);
    addPreferencesFromResource(R.xml.preferences);
    keys = getResources().getStringArray(R.array.prefKeys);
    p = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    //Gets the keys of the preferences
    for (int i = 0; i < keys.length; i++) {
    setSummary(p, keys[i]);
    }
    }   

   //Listener to detect changes             
   public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                    String key) {
   Preference p = findPreference(key);
   if (p instanceof EditTextPreference) {
   p.setSummary(sharedPreferences.getString(key,(String) p.getSummary()));
   }
   else if (p instanceof ListPreference) {
   p.setSummary((String) ((ListPreference) p).getEntry());
   }
   }
   //First time initialization     
   private void setSummary(SharedPreferences sharedPreferences, String key) {
   Preference p = findPreference(key);
   if (p instanceof EditTextPreference) {
    //This was the mistake I did
   //p.setSummary(sharedPreferences.getString(key,(String) p.getSummary()));
   p.setSummary(((EditTextPreference) p).getText());
   }
  else if (p instanceof ListPreference) {
   //This was the mistake I did
  //p.setSummary((String) ((ListPreference) p).getEntry());         
  p.setSummary((String) ((ListPreference) p).getEntry());
  }
  }
  }
4

2 回答 2

1

你在谈论两个不同的话题。

首先,您有 SharedPreferences 对象,如指南所述,它必须且只能通过 SharedPreferences.Editor 对象进行编辑。请参阅以下位:

/**
 * This function writes the user's current score to persistent storage via {@link SharedPreferences}
 * @param key The Key to store the value with, this is the same value that must be used to retrieve the preference value at a later time. 
 * @param value The Actual Value to store for the supplied key. 
 */
private void saveScore (String key, int value) {
    //First, get the instance of the SharedPreference, this is a default file that has the Package name as it's own file name. 
    SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    //Get an instance of an editor by calling .edit()
    SharedPreferences.Editor mEditor= mPreferences.edit();

    //stage the changes
    mEditor.putBoolean("your-key", true || false);
    //Call commit to persit changes
    mEditor.commit();       
}

当您谈论 时onSharedPreferenceChanged,这只是一个界面,可让您知道 SharedPreference 何时发生更改,它实际上并不编写/编辑首选项文件。

当与 a或 a一起使用时,该onSharedPreferenceChanged界面特别有用,可根据当前用户偏好的更改在需要时对用户界面进行更改。PreferenceActivityPreferenceFragment

例如看这个:

public class Settings extends PreferenceActivity {

/**
 * The Key to be used to access the preference. This should be defined already on your preferences.xml file
 */
public static final String KEY_CURRENT_THEME = "pref_current_theme";
/**
 * The instance of the Theme Preference. 
 */
Preference mThemePreference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Find the preference
    mThemePreference = findPreference(KEY_CURRENT_THEME);
    //Set the listener
    mThemePreference.setOnPreferenceChangeListener(mOnPreferencedChanged);
    //Call onPrerenceChanged to begin with in case the settings may have changed
    //The system will call this later each time the preference gets updated by the user via Settings
    mChangeListener.onPreferenceChange(
            mThemePreference,
            PreferenceManager.getDefaultSharedPreferences(
                    mThemePreference.getContext()).getString(mThemePreference.getKey(),
                            ""));   
}

private OnPreferenceChangeListener mOnPreferencedChanged = new OnPreferenceChangeListener() {

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        Resources mResources = preference.getContext().getResources();

        //You can check to see what change in two different ways.           
        //a) you can check the TypeOf the preference that changed. 
        if (preference instanceof CheckBoxPreference) {
            //If the preference that changes is a CheckBoxPreference, then do such and such changes. 
        } 
        //Or, you can check if it's a specific preference that changed

        if (preference == mThemePreference) {
            //If the preference is actually the Theme Preference itself, then do such and such changes. 
        }

        //Always return true so that the preference value change can be persisted, false otherwise. 
        return true;
    }
};

我希望这有帮助!:)

编辑

您的问题:首选项文件存储在哪里,我如何访问它?

在哪里?PreferenceActivity通过 a 、 aPreferenceFragment或通过调用创建/编辑的文件PreferenceManager.getDefaultSharedPreferences(context)存储在 /data/data/your.package.name/shared_prefs/your.package.name_preferences.xml

但是,该文件的存储位置与作为开发人员的您无关,因为您只能通过调用PreferenceManager.getDefaultSharedPreferences(context)

例如,假设您有一个CheckBoxPreference定义是使用 Holo Dark 还是 Holo Light 作为您活动的主题,例如,看起来像这样:

复选框首选项

每次用户选中或取消选中首选项时,系统都会将该更改保存到上面为您讨论的默认首选项文件中,您无需手动保存此更改,因为它已经为您完成了。

如果您想做的不仅仅是持久化更改,您可以通过实现我上面提供的来拦截事件,您甚至可以通过返回持久化或不持久OnPreferenceChangeListener化来告诉系统是否应该持久化更改。truefalse

如何访问它? 为了知道主题偏好的当前值是多少,比如说根据偏好值实际应用 UI 更改,您可以执行以下操作:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        //We update the preference dependent values **before** setting the content view
    updatePrefDependentValues();
    setContentView(R.layout.activity_empty_container);
    }

private void updatePrefDependentValues() {
    //get the instance of the SharedPreference Object. 
    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    //Update the boolean value based on the current preferences
    //The second parameter to getBoolean is a default value, we want false as default value. 
    mUseDarkTheme = mPreferences.getBoolean("whatever_key_you_set_for_this_preference", false);
    if (mUseDarkTheme) {
        //If we are using dark theme, set such theme. 
        setTheme(R.style.DarkTheme);
    }
    else if (!mUseDarkTheme) {
        //If we are **not** using dark theme, set light theme.
        setTheme(R.style.LightTheme);
    }
}

如果您还有其他问题,请告诉我。

编辑三:

您不需要访问 Eclipse 上的文件,我想您想打开它来设置默认值,嗯,这就是preferences.xml 文件的用途。

想象一下,您将在设置上有一些东西,您有一个CheckBoxPreference主题,就像上面一样,您还有一个CheckBoxPreference用于启用和禁用后台同步,并且您有一个ListPreference用于存储在后台同步的频率。

上述所有设置都必须声明为默认值,在 a 的情况下CheckBoxPreference,默认值为布尔值,true 或 false,在 aListPreference的情况下,默认值是您想要的任何值,具体取决于您提供给条目的值。

例如,这是一个非常简单的preference.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Preference Categories are a good way to keep your Settings organized -->
<!-- android:key represents a String that is used to write and read from the preference file stored at /data/data/your.package.name -->
<PreferenceCategory
    android:title="@string/pref_title_general"
    android:key="pref_title_general"         
    >
    <!-- CheckBoxPreference are pretty simple, they only need a title, a key and a default value -->
    <!-- android:key is a MUST in each Preference as otherwise the system cannot persist changes to it.  -->
    <!-- android:key would be the same String you pass a "Key" 
    when calling mPreference.getBoolean(String key, Boolean default) from the Activity -->
    <CheckBoxPreference
        android:title="@string/pref_title_enable_dark_theme"
        android:key="pref_key_dark_theme"       
        android:defaultValue="false"                              
        />

</PreferenceCategory>

<PreferenceCategory
    android:title="@string/pref_title_sync_preferences"
    android:key="pref_title_navigation"         
    >

    <CheckBoxPreference
        android:title="@string/pref_title_enable_background_sync"
        android:key="pref_key_background_sync"       
        android:defaultValue="false"                              
        />

    <!-- ListPreference are a bit more complex, they require a Key to persist the changes
        android:entries represents the values displayed to the user when setting the preference
        android:entryValues represent the values that will be persisted, this array is the same size as the entries one.
        For instance, an Entry could be "Every 10 Minutes", and the entry value would be: "10" or "ten"
        This also requires a default value, which in this case MUST be a part of the entryValues array.   
        -->
    <ListPreference
        android:title="@string/pref_title_sync_frequency"
        android:key="pref_key_sync_frequency"
        android:entries="@array/pref_entries_sync_frequency"  
        android:entryValues="@array/pref_entries_values_sync_frequency" 
        android:defaultValue="@string/pref_default_sync_frequency"         
        />

</PreferenceCategory>

同样,如果您使用 a PreferenceActivityorPreferenceFragment正确,则用户所做的更改将被保留,并且您实际上不需要做任何事情来在用户下次访问设置时进行更改。

如果您想了解有关设置和首选项的更多信息,请参阅以下内容:http: //developer.android.com/guide/topics/ui/settings.html

现在,如果您要做的是持久化其他数据,这些数据可能不会显示在PreferenceActivity或上PreferenceFragment,比如用户名或电子邮件地址,那么您可以通过 saveScore 示例按照上述方式进行持久化。

这是有关 SharedPreferences 更多信息的链接:http: //developer.android.com/training/basics/data-storage/shared-preferences.html

于 2013-04-08T13:03:57.047 回答
1

Preference并且SharedPreferences不一样。但是,它们经常一起使用。

Preference是用于显示和编辑用户首选项的 UI 类。

SharedPreferences是用于持久化应用程序设置的非 UI 类。要更改这些设置,您需要使用 获取一个SharedPreferences.Editor实例,edit()然后使用 存储更改commit()

通常,Preference值存储在SharedPreferences.

于 2013-04-08T12:51:40.050 回答