繁体   English   中英

android + sharedPreferences

[英]android + sharedPreferences

API是android的新手,目前正在使用“偏好设置”时,我有以下疑问,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, ""));    
    }
}

那么在不使用edit和commit的情况下编辑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());
  }
  }
  }

PreferenceSharedPreferences不同。 但是,它们经常一起使用。

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

SharedPreferences是用于保留应用程序设置的非UI类。 要对这些设置进行更改,请使用edit()获得一个SharedPreferences.Editor实例,然后使用commit()存储所做的更改。

通常, Preference值存储在SharedPreferences

您正在谈论冠军的两个不同主题。

首先,您具有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何时获得更改,它实际上并未写入/编辑首选项文件。

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;
    }
};

我希望这有帮助! :)

编辑

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

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

但是,此文件的存储位置开发人员无关 ,因为您应通过调用PreferenceManager.getDefaultSharedPreferences(context)来访问此文件。

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

CheckBox首选项

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

如果您要做的不仅仅是保留更改,还可以通过实现我上面提供的OnPreferenceChangeListener来拦截事件,甚至可以通过返回true来保留,或者返回false来告诉系统是否应保留更改。不坚持。

如何访问? 为了知道主题首选项的当前值是什么,例如说要根据首选项值实际应用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用于存储后台同步的频率。

以上所有设置都必须声明为默认值,如果使用CheckBoxPreference ,则默认值为布尔值,是true或false;如果使用ListPreference则默认值为您想要的值,取决于您提供给条目的值。

例如,这是一个非常简单的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>

同样,如果您正确使用PreferenceActivityPreferenceFragment ,则用户所做的更改将被保留,并且实际上您无需做任何更改即可在下次用户访问设置时进行更改。

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

现在 ,如果您要保留其他数据,而这些数据可能未显示在PreferenceActivityPreferenceFragment ,例如用户名或电子邮件地址,那么您可以如上所述通过saveScore示例进行持久化。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM