Android提供了SharedPreferences對(duì)象,以幫助你保存簡(jiǎn)單的應(yīng)用程序數(shù)據(jù)。
使用SharedPreferences對(duì)象,可以通過(guò)使用name/value對(duì)保存所需的數(shù)據(jù)。
在以下代碼中,你將了解如何使用SharedPreferences對(duì)象進(jìn)行存儲(chǔ)應(yīng)用數(shù)據(jù)。
在res/xml/myapppreferences.xml中創(chuàng)建一個(gè)文件并填充myapppreferences.xml文件,如下所示:
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Category 1"> <CheckBoxPreference android:title="Checkbox" android:defaultValue="false" android:summary="True or False" android:key="checkboxPref" /> </PreferenceCategory> <PreferenceCategory android:title="Category 2"> <EditTextPreference android:summary="Enter a string" android:defaultValue="[Enter a string here]" android:title="Edit Text" android:key="editTextPref" /> <RingtonePreference android:summary="Select a ringtone" android:title="Ringtones" android:key="ringtonePref" /> <PreferenceScreen android:title="Second Preference Screen" android:summary= "Click here to go to the second Preference Screen" android:key="secondPrefScreenPref" > <EditTextPreference android:summary="Enter a string" android:title="Edit Text (second Screen)" android:key="secondEditTextPref" /> </PreferenceScreen> </PreferenceCategory> </PreferenceScreen>
Java代碼
import android.os.Bundle; import android.preference.PreferenceActivity; //from m.o2fo.com public class AppPreferenceActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //load the preferences from an XML file addPreferencesFromResource(R.xml.myapppreferences); } }
一旦你修改了至少一個(gè)首選項(xiàng)的值,就會(huì)在Android模擬器的/data/data/cn.w3cschool.your activity name/shared_prefs
文件夾中創(chuàng)建一個(gè)文件。
更多建議: