Android 首选项
2018-02-21 15:18 更新
Android提供了SharedPreferences对象,以帮助你保存简单的应用程序数据。
使用SharedPreferences对象,可以通过使用name/value对保存所需的数据。
在以下代码中,你将了解如何使用SharedPreferences对象进行存储应用数据。
例子
在res/xml/myapppreferences.xml中创建一个文件并填充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 www.w3cschool.cn
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);
}
}注意
一旦你修改了至少一个首选项的值,就会在Android模拟器的/data/data/cn.w3cschool.your activity name/shared_prefs文件夹中创建一个文件。
以上内容是否对您有帮助:

免费 AI IDE


更多建议: