簡體   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