本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


下面展示如何使用SharedPreferences对象去保存应用的数据。你也将会看见通过特殊的Activity去修改已经被保存的应用数据。

1. 新建一个工程,UsingPreferences。

2. 在res文件夹下面新建一个文件夹,xml。在新建的文件夹中新建一个文件,myappreferences.xml。

3. 在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>
4. 在包路径下面新建一个类,AppPreferenceActivity。

5. AppPreferenceActivity中的代码。

public class AppPreferenceActivity extends PreferenceActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                PreferenceManager prefMgr = getPreferenceManager();        prefMgr.setSharedPreferencesName("appPreferences");        //---load the preferences from an XML file---        addPreferencesFromResource(R.xml.myapppreferences);    }}
6. 在AndroidManifest.xml中添加AppPreferenceActivity类的入口。

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="net.manoel.UsingPreferences"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="10" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".UsingPreferencesActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".AppPreferenceActivity"                  android:label="@string/app_name">            <intent-filter>                <action                     android:name="net.manoel.AppPreferenceActivity" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>                </application></manifest>
7. main.xml中的代码。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" ><Buttonandroid:id="@+id/btnPreferences"android:text="Load Preferences Screen"android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickLoad"/><Buttonandroid:id="@+id/btnDisplayValues"android:text="Display Preferences Values"android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClickDisplay"/><EditText  android:id="@+id/txtString"  android:layout_width="fill_parent" android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btnModifyValues"android:text="Modify Preferences Values"android:layout_width="fill_parent" android:layout_height="wrap_content"android:onClick="onClickModify"/>    </LinearLayout>
8. 在UsingPreferencesActivity.java中添加一些代码。

public class UsingPreferencesActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);}public void onClickLoad(View view) {Intent i = new Intent("net.manoel.AppPreferenceActivity");startActivity(i);}}
9. 按F11在模拟器上面测试。点击最上面的按钮,跳转到UsingPreferences这个界面。

10. 点击CheckBox,让它的状态在checked和unchecked之间进行切换。观察CATEGORY 1和CATEGORY 2。点击Edit Text,输入一些字符,然后按OK把对话框消失掉。

11. 点击Ringtones,选择默认的铃声或静音。如果在真机上面测试的话,可能会有更多的选项。

12. 点击Second Preference Screen,就会跳转到下一屏。

13. 如果想要返回上一屏,可以按Back键。

14. 一旦你修改了选项中的任何一项,在/data/data/net.manoel.UsingPreferences/shared_prefs文件夹下面就会新建一个文件。可以使用DDMS进行查看。

15. 如果你把这个文件打开的话,会看见类似的内容。

更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. 一款常用的 Squid 日志分析工具
  3. GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
  4. RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
  5. Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
  6. Android(安卓)获取源码
  7. Drawable、Bitmap、byte[]之间的转换 (转)
  8. android assert 自定义格式被压缩
  9. eclipse中跳转查看android类的源码

随机推荐

  1. 校招录取之后前往公司实习,现在感觉自己前
  2. 如何将dict转换为spark map输出
  3. 当使用一个传送到另一个的python文件时,我
  4. matplotlib绘制符合论文要求的图片
  5. classmethod,staticmethod,还有类里面一般
  6. Python文件操作大全,随机删除文件夹内的任
  7. 获取错误“ValueError:int()的无效文字,基数
  8. C++各大有名库的介绍——准标准库Boost
  9. 从Python中的列表元素中删除URL
  10. python传递列表作为函数参数