http://blog.csdn.net/Android_Tutor/article/details/5531849

大家好,我们这一节讲的是Android Preferences 的学习,Preferences 在Android当中被用来记录应用,以及用户喜好等等,它可以用来保存

简单的数据类型,如Int,Double,Boolean等。Preferences中保存的数据可以理解为Map型。我们通过PreferenceManager 以及getDefaultSharedPreferences(Context) 来获取它,比如当我们想获得整数我们可以用 getInt(String key, int defVal) .获取里面的某个键值,当我们想修改时候我们用putInt(String key, int newVal), 最后用 edit(), 方法提交!千万不要忘记了哦~

为了让大家跟好的理解我做了一个简单的Demo,程序主要有个TextView控件,上面写着用户使用改应用的次数。效果如下图所示:

下面是实现Demo的大体步骤:

一、新建一个Android工程命名为:PreferencesDemo。

二、在修改main.xml布局文件,这里只是在TextView控件里加了一个id.代码如下:

[java] view plaincopy

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:id="@+id/text"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:text="@string/hello"
  12. />
  13. </LinearLayout>

三、修改PreferenceDemo.java的代码,全部代码如下:

[java] view plaincopy

  1. package com.android.tutor;
  2. import android.app.Activity;
  3. import android.content.SharedPreferences;
  4. import android.os.Bundle;
  5. import android.preference.PreferenceManager;
  6. import android.widget.TextView;
  7. public class PreferencesDemo extends Activity {
  8. /** Called when the activity is first created. */
  9. @Override
  10. public void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.main);
  13. SharedPreferences mPerferences = PreferenceManager
  14. .getDefaultSharedPreferences(this);
  15. int counter = mPerferences.getInt("counter", 0);
  16. TextView mTextView = (TextView)findViewById(R.id.text);
  17. mTextView.setText("This app has been started " + counter + " times.");
  18. SharedPreferences.Editor mEditor = mPerferences.edit();
  19. mEditor.putInt("counter", ++counter);
  20. mEditor.commit();
  21. }
  22. }

四、运行代码,实现上述效果.

五、查看Preferences文件,首先打开命令终端:adb shell一下,然后cd data/data进入该目录,ls一下我们会发现一大堆包文件,入下图所示:

cd com.android.tutor (这里是我程序的包名) /shared_prefs,ls一下会发现.xml文件如下图:

打开.xml文件,格式如下(为什么这样大家自己去理解):

[java] view plaincopy

  1. <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
  2. <map>
  3. <int name="counter" value="3" />
  4. </map>

OK,今天就到此为止,以上全是个人愚见,如果有什么地方不对的,请指正,谢谢大家!

更多相关文章

  1. Android之NDK开发
  2. android selector 背景选择器
  3. Android中的File文件存储及读取file中的Bitmap
  4. Android创建隐藏文件或者文件夹
  5. Android之NDK开发
  6. android 静音与振动
  7. 转:善用Android预定义样式来为我们的布局设置效果,大大节约代码量
  8. Android(安卓)File类
  9. imageView的使用(进行原样的保持和按照比例的缩放:)

随机推荐

  1. android调用系统发短信界面功能
  2. Android(安卓)requires compiler complia
  3. Android(安卓)studio生成APK打包,修改生成
  4. Android(安卓)支持的文件类型
  5. android 实现button的背景改变
  6. Step Detector and Step Counter Sensors
  7. Android控件属性大全
  8. android布局属性大全
  9. lua学习笔记 1 android 调用Lua, Lua脚本
  10. Android——PopupWindow