fragment实例怎么实例化sharedpreferences

  SharedPreferences是Android中存储简单数据的一个工具类。可以想象它是一个小小的Cookie,它通过用键值对的方式把简单数据类型(boolean、int、float、long和String)存储在应用程序的私有目录下(data/data/包名/shared_prefs/)自己定义的xml文件中。
  它提供一种轻量级的数据存储方式,通过eidt()方法来修改里面的内容,通过Commit()方法来提交修改后的内容。
二、重要方法
public abstract boolean contains (String key) :检查是否已存在该文件,其中key是xml的文件名。
edit():为preferences创建一个编辑器Editor,通过创建的Editor可以修改preferences里面的数据,但必须执行commit()方法。
getAll():返回preferences里面的多有数据。
getBoolean(String key, boolean defValue):获取Boolean型数据
getFloat(String key, float defValue):获取Float型数据
getInt(String key, int defValue):获取Int型数据
getLong(String key, long defValue):获取Long型数据
getString(String key, String defValue):获取String型数据
registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener):注册一个当preference发生改变时被调用的回调函数。
unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener):删除当前回调函数。
三、重要接口SharedPreferences.Editor
  1.简介
  用于修改SharedPreferences对象的内容,所有更改都是在编辑器所做的批处理,而不是复制回原来的SharedPreferences或持久化存储,直到你调用commit(),才将持久化存储。
  2.重要方法
  clear():清除内容。
  commit():提交修改
  remove(String key):删除preference
下面通过&记住密码&功能
  效果图如下
登录成功后的页面
当第一次登录点击&记住密码&后,第二次打开时的页面
布局文件 login.xml
&?xml version="1.0" encoding="utf-8"?&&LinearLayout xmlns:android=""&android:layout_width="fill_parent" android:layout_height="fill_parent"&android:gravity="right" android:layout_gravity="right"&android:background="@drawable/default_bg" android:orientation="vertical"&&&TableLayout android:layout_width="fill_parent"&&android:layout_height="wrap_content" android:stretchColumns="1"&&&&TableRow android:gravity="center" android:layout_gravity="center"&&&&&ImageView android:layout_width="fill_parent" &&&&android:layout_height="wrap_content" android:id="@+id/ivlogo"&&&&&&&&&/ImageView&&&&/TableRow&&&/TableLayout&&&TableLayout android:layout_width="fill_parent"&&android:layout_height="wrap_content" android:stretchColumns="1"&&&&TableRow android:layout_marginTop="100dip"&&&&&TextView android:layout_width="wrap_content"&&&&android:layout_marginLeft="20dip" android:gravity="center_vertical"&&&&android:layout_height="wrap_content" android:id="@+id/tvaccount"&&&&android:text="帐号:" android:textSize="20sp"&&&&&/TextView&
&&&&EditText android:layout_width="70px" android:layout_height="wrap_content"&&&&android:id="@+id/etaccount" android:layout_marginRight="20dip"&&&&android:maxLength="20"&&/EditText&&&&/TableRow&&&&TableRow android:layout_marginTop="10dip"&&&&&TextView android:layout_width="wrap_content"&&&&android:layout_height="wrap_content" android:id="@+id/tvpw"&&&&android:layout_marginLeft="20dip" android:gravity="center_vertical"&&&&android:text="密码:" android:textSize="20sp"&&&&&/TextView&
&&&&EditText android:layout_width="70px" android:layout_height="wrap_content"&&&&android:layout_marginRight="20dip" android:id="@+id/etpw"&&&&android:inputType="textPassword"&&/EditText&&&&/TableRow&&&/TableLayout&&LinearLayout xmlns:android=""&&android:layout_width="wrap_content" android:layout_height="wrap_content"&&android:orientation="horizontal" android:layout_marginTop="5dip" android:layout_marginRight="20dip"&&&&&TextView android:layout_width="wrap_content"&&&android:layout_height="wrap_content" android:id="@+id/tvclear"&&&android:text="清除Cookies" android:textColor="#aa0000" android:textSize="12px"&&/TextView&&&&&/LinearLayout&&&TableLayout android:layout_width="fill_parent"&&android:layout_height="wrap_content" android:layout_marginTop="20dip"&&&&TableRow android:gravity="center" android:layout_width="fill_parent"&&&&&Button android:layout_width="100px" android:layout_height="wrap_content"&&&&android:id="@+id/btnlogin" android:layout_gravity="center"&&&&android:text="登录"&&/Button&
&&&&Button android:layout_width="100px" android:layout_height="wrap_content"&&&&android:id="@+id/btnexit" android:layout_gravity="center"&&&&android:text="退出"&&/Button&&&&/TableRow&&&/TableLayout&
&&LinearLayout xmlns:android=""&&android:layout_width="wrap_content" android:layout_height="wrap_content"&&android:orientation="horizontal" android:layout_marginTop="25dip"&
&&&CheckBox android:layout_width="wrap_content"&&&android:layout_height="wrap_content" android:id="@+id/cbrp"&&&android:text="记住密码" android:textSize="12px"&&/CheckBox&&&&CheckBox android:layout_width="wrap_content"&&&android:layout_height="wrap_content" android:id="@+id/cbal"&&&android:text="自动登录" android:textSize="12px"&&/CheckBox&&&/LinearLayout&&/LinearLayout&
package com.
import android.app.Aimport android.content.Cimport android.content.SharedPimport android.os.Bimport android.util.Limport android.view.Dimport android.view.Vimport android.view.View.OnClickLimport android.widget.Bimport android.widget.CheckBimport poundBimport android.widget.EditTimport android.widget.TextVimport android.widget.T
import com.wjq.beans.Uimport com.wjq.func.UserM
public class Login extends Activity {&private EditText etA&private EditText etPW;&private Button btnL&private Button btnE&private CheckB&private CheckB&private UserMgr userM&private U&private SharedP&private TextView tvC
&/*& * (non-Javadoc)& * & * @see android.app.Activity#onCreate(android.os.Bundle)& */&@Override&protected void onCreate(Bundle savedInstanceState) {&&// TODO Auto-generated method stub&&super.onCreate(savedInstanceState);
&&setContentView(R.layout.login);
&&etAccount = (EditText) findViewById(R.id.etaccount);&&etPW = (EditText) findViewById(R.id.etpw);&&cbrp = (CheckBox) findViewById(R.id.cbrp);&&cbal = (CheckBox) findViewById(R.id.cbal);&&btnLogin = (Button) findViewById(R.id.btnlogin);&&btnExit = (Button) findViewById(R.id.btnexit);&&tvClear=(TextView)findViewById(R.id.tvclear);&&InitConfig();&&cbrp&&&&.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
&&&&&@Override&&&&&public void onCheckedChanged(CompoundButton buttonView,&&&&&&&boolean isChecked) {&&&&&&sp = getSharedPreferences("UserInfo", 0);&&&&&&sp.edit().putBoolean("cbrp", isChecked).commit();&&&&&}
&&cbal&&&&.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
&&&&&@Override&&&&&public void onCheckedChanged(CompoundButton buttonView,&&&&&&&boolean isChecked) {&&&&&&sp = getSharedPreferences("UserInfo", 0);&&&&&&sp.edit().putBoolean("cbal", isChecked).commit();&&&&&}
&&&&});&&btnLogin.setOnClickListener(new OnClickListener() {
&&&@Override&&&public void onClick(View v) {&&&&user = new User(etAccount.getText().toString(), etPW.getText()&&&&&&.toString());
&&&&Log.i("tag", "Account:" + etAccount.getText().toString());&&&&Log.i("tag", "Password:" + etPW.getText().toString());
&&&&userMgr = new UserMgr();&&&&Boolean flag = userMgr.CheckUser(user, Login.this);
&&&&if (!flag) {&&&&&Toast.makeText(Login.this, "用户验证错误!", 1000).show();&&&&}
&&&&else {&&&&&if (cbrp.isChecked()) {&&&&&& sp = getSharedPreferences("UserInfo",&&&&&&&&Context.MODE_WORLD_WRITEABLE&&&&&&&&&&| Context.MODE_WORLD_READABLE);&&&&&&&&&&&&sp.edit().putString("account",&&&&&&&&etAccount.getText().toString()).commit();&&&&&&sp.edit().putString("password",&&&&&&&&etPW.getText().toString()).commit();&&&&&}&&&&}&&&}
&&btnExit.setOnClickListener(new OnClickListener() {
&&&@Override&&&public void onClick(View v) {&&&&System.exit(0);&&&}&&});&&&&tvClear.setOnClickListener(new OnClickListener(){
&&&@Override&&&public void onClick(View v) {sp=getSharedPreferences("UserInfo", 0);&&&&&&&&sp.edit().clear().commit();&&&}});&}
//初始化配置
&private void InitConfig() {&&sp = getSharedPreferences("UserInfo", 0);&&etAccount.setText(sp.getString("account", null));&&etPW.setText(sp.getString("password", null));&&cbal.setChecked(sp.getBoolean("cbal", false));&&cbrp.setChecked(sp.getBoolean("cbrp", false));&}}
&sp = getSharedPreferences("UserInfo", 0);&&&&&&sp.edit().putBoolean("cbal", isChecked).commit();&&&&&UserInfo是指xml文件的文件名,如果此文件已存在则直接向其中写内容&isChecked&的值,首先通过SharedPreferences的edit()方法创建editor,然后调用commit()方法提修改
sp = getSharedPreferences("UserInfo", 0);&&etAccount.setText(sp.getString("account", null));&&etPW.setText(sp.getString("password", null));&&cbal.setChecked(sp.getBoolean("cbal", false));&&cbrp.setChecked(sp.getBoolean("cbrp", false));&
阅读(...) 评论()Android中PreferenceFregment使用完全攻略
第2页_Linux编程_Linux公社-Linux系统门户网站
你好,游客
Android中PreferenceFregment使用完全攻略
来源:Linux社区&
作者:silangquan
2.创建一个activity用于给PreferenceFragment 依附
package com.example.
import android.app.Aimport android.os.B
public class SetPreferenceActivity extends Activity {
&@Override&protected void onCreate(Bundle savedInstanceState) {& // TODO Auto-generated method stub& super.onCreate(savedInstanceState);& & getFragmentManager().beginTransaction().replace(android.R.id.content,& & & & & & & & new PrefsFragment()).commit();&}
3.创建PreferenceFragment
package com.example.andro
import android.annotation.SuppressLimport android.content.SharedPimport android.content.SharedPreferences.OnSharedPreferenceChangeLimport android.os.Bimport android.preference.Pimport android.preference.PreferenceFimport android.preference.Preference.OnPreferenceChangeL
@SuppressLint("NewApi")public class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener{
&@Override&public void onCreate(Bundle savedInstanceState) {& // TODO Auto-generated method stub& super.onCreate(savedInstanceState);
& // Load the preferences from an XML resource& addPreferencesFromResource(R.xml.preferences);&}
&@Override&public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {& // TODO Auto-generated method stub& // Set summary to be the user-description for the selected value& if(!key.equals(MainActivity.PRF_CHECK))& {& &Preference connectionPref = findPreference(key);& &connectionPref.setSummary(sharedPreferences.getString(key, ""));& }&}
&@Override&public void onResume() {& super.onResume();& getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
&@Override&public void onPause() {& getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);& super.onPause();&}
implements OnSharedPreferenceChangeListener 是用于监听SharedPreference是否改变的。这里主要的作用是当SharedPreference改变的时候及时更新界面中preference的summary,提供一个更好的交互。注意在OnResume和OnPause中要注册和卸载监听器,维护activity中的生命周期。
注:不能给每个preference设置OnChangeListener来更新界面中preference的summary,这样会阻止系统存储preference.xml.2
相关资讯 & & &
图片资讯 & & &
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款&span style=&font-family:Microsoft YaHfont-size:48&&&span style=&background-color: rgb(255, 204, 204);&&SharedPreferences&/span&&/span&
就快要找实习了,我才研究到这里,真是拙计啊...
网上看到一篇我认为比较好的文章,转过来添加一些自己学的额外的东西。
===========================
SharedPreferences存储类效率分析
SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长整形、Int整形、String字符串型的保存,它是什么样的处理方式呢?
&SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问,android123提示最终是以xml方式来保存,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。xml处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。
--------------------------------------------------------------------------------------------------------------------------
SharedPreferences 的用法
2个activity 之间的数据传递除了可以他通过intent来传递,还可以使用SharedPreferences来共享数据的方式
SharedPreferences 用法很简单.
记得使用commit()方法来写入数据(该方法会阻止调用线程,并在成功写入后返回true,在写入失败时返回false)。
或者可以调用Apply()方法(这个方法是安全地异步写入SharedPreferences
Editor,首选此方法)
另外SharedPreferences的getAll方法,可返回所有可用的SharedPreferences键值的一个映射Map&String,?&
另外可通过SharedPreferences的contains方法,检查是否存有某个键。
Android 数据存储
这种方式应该是用起来最简单的Android读写外部数据的方法了。他的用法基本上和J2SE(java.util.prefs.Preferences)中的用法一样,以一种简单、透明的方式来保存一些用户个性化设置的字体、颜色、位置等参数信息。一般的应用程序都会提供“设置”或者“首选项”的这样的界面,那么这些设置最后就可以通过Preferences来保存,而程序员不需要知道它到底以什么形式保存的,保存在了什么地方。当然,如果你愿意保存其他的东西,也没有什么限制。只是在性能上不知道会有什么问题。
在Android系统中,这些信息以XML文件的形式保存在&/data/data/PACKAGE_NAME/shared_prefs&目录下。
String PREFS_NAME = &Note.&;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean(&silentMode&, false);
String hello = settings.getString(&hello&, &Hi&);
这段代码中:
String PREFS_NAME = &Note.&;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(&silentMode&, true);
editor.putString(&hello&, &Hello~&);
有了上面数据读取的代码,这里面的就容易理解了,只是别忘了最后的commit();
访问接口和优先修改数据,并由getSharedPreferences(String,int)返回数据,为了统一设置参数,有一个单例类供所有的客户端共享.修改参数必须通过一个SharedPreferences.Editor对象,在存储他们时,以确保参数值有统一的状态和控制
目前此类不支持多线程,
一个首选项框架和Preference Activity
Preference Activity框架由4部分组成
Preference Screen 布局:
&&&&&&& 一个XML文件,定义了在Preference Screen中的显示的层次结构。它指定了要显示的文本及其控件,所允许的值和为每个控件使用的Shared Preference键。
&&&&&&& 存储在res/xml资源文件中。
&&&&&&& 使用Intent在Preference Screen中导入系统首选项。
Preference Activity和 Preference Fragment:分别是Preference Activity和 Preference Fragment的扩展,用于包含Preference
Preference Header定义:一个XML文件,定义了应用程序的Preference Fragment,以及用于显示Preference Fragment的层次结构。
Shared Preference 变化监听程序:一个onSharedPreferenceChangeListener类的实现,用于监听Shared Preference的变化。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1375次
排名:千里之外
原创:25篇

我要回帖

更多关于 java preferences 的文章

 

随机推荐