首页 > 代码库 > SharedPreferences的使用

SharedPreferences的使用

本文介绍SharedPreferences及PreferenceActivity、PreferenceFragment。

1、SharedPreferences简单使用示例

public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setContentView(R.layout.activity_main);
		//all apps sharing the same user ID
		SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		//save 5 kinds of datas: boolean,int,long,float,String
		editor.putBoolean("isMan", true);
		editor.putFloat("weight", 68f);
		editor.putInt("age", 25);
		editor.putLong("salary", 10000L);
		editor.putString("name", "Victor");
		Set<String> relatives = new HashSet<String>();
		editor.putStringSet("relatives", relatives);
//		editor.apply();//asynchronous,main thread
		long start = SystemClock.elapsedRealtime();
		editor.commit();
		Log.i(TAG, "commit:"+(SystemClock.elapsedRealtime()-start)+"ms");
	}
	public void onClick(View v){
		switch (v.getId()) {
		case R.id.btn:
			Log.i(TAG, "getLocalClassName()="+getLocalClassName());
			SharedPreferences sp = getSharedPreferences(getLocalClassName(), Context.MODE_PRIVATE);
			sp.getBoolean("isMan", false);
			sp.getFloat("weight", 60);
			sp.getInt("age", 16);
			sp.getLong("salary", 6000L);
			sp.getString("name", "none");
			sp.getStringSet("relatives", null);
			Map<String, ?> map = sp.getAll();
			if(sp.contains("salary")){
				long salary = (Long) map.get("salary");
				Log.i(TAG, "contains:"+salary);
			}
		}
	}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button 
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get"
        android:onClick="onClick"/>
</LinearLayout>

2、PreferenceActivity、PreferenceFragment使用示例

1) MyFragmentPreferenceActivity.java

public class MyFragmentPreferenceActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
	private static final String TAG = MyFragmentPreferenceActivity.class.getSimpleName();
	@Override
	public void onBuildHeaders(List<Header> target) {
		super.onBuildHeaders(target);
		loadHeadersFromResource(R.xml.preferenceheaders, target);
		//getPackageName()+"_preferences"
		SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		sharedPreferences.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if(key.equals("CheckBox")){
			boolean value = http://www.mamicode.com/sharedPreferences.getBoolean(key, false);>2) preferenceheaders.xml

preference-headers作为顶级标签,包含多个header

<?xml version="1.0" encoding="utf-8"?>
<preference-headers
    xmlns:android="http://schemas.android.com/apk/res/android">
    <header
        android:fragment="com.qinuli.buttontest2.MyPreferenceFragment"
        android:title="My header"
        android:icon="@drawable/ic_launcher"
        android:summary="description of header"/>
    <header
        android:title="Intent"
        android:summary="launch an intent">
        <intent android:action="android.settings.DISPLAY_SETTINGS"/>
    </header>
</preference-headers>
3) MyPreferenceFragment.java
public class MyPreferenceFragment extends PreferenceFragment {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.userpreferences);
	}
}
4) userpreferences.xml

PreferenceScreen作为顶级标签,包含多个PreferenceCategory

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory 
        android:title="Category1">
        <CheckBoxPreference 
            android:key="CheckBox"
            android:title="CheckBox"
            android:summaryOn="laugh"
            android:summaryOff="cry"
            android:defaultValue=http://www.mamicode.com/"true"/>>5) strings.xml

ListPreference引用的资源

<resources>

    <string name="app_name">ButtonTest2</string>
	<string-array name="mylist">
	    <item >good</item>
	    <item >great</item>
	    <item >nice</item>
	    <item >fine</item>
	    <item >beautiful</item>
	    <item >pretty</item>
	</string-array>
	<string-array name="myvalues">
	    <item >_GOOD</item>
	    <item >_GREAT</item>
	    <item >_NICE</item>
	    <item >_FINE</item>
	    <item >_BEAUTIFUL</item>
	    <item >_PRETTY</item>
	</string-array>
</resources>

SharedPreferences的使用