①简单存储
SharedPreferences
SharedPreferences对象本身只能获取数据而不支持存储和修改,存储、修改是通过SharedPreferences.edit()获取的内部接口Editor()对象来实现的。
SharedPreferences支持三种访问模式:
name | MODE |
---|---|
私有 | MODE_PRIVATE |
全局读 | MODE_WORLD_READABLE |
全局写 | MODE_WORLD_WRITEABLE |
话不多说,接下来直接干!我们来实现一个有记住密码的登录界面:
对应布局文件(activity_main.xml)
在MainActvity的onCreate()里先获所有控件、实例化SharedPreferences和SharedPreferences.Editor、给两个按钮都注册击事件,代码如下:
TextView tv_name,tv_password;
EditText edit_name,edit_passwprd;
Button stratButton,cancelButton;
CheckBox checkBox;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_name = (TextView)findViewById(R.id.name);
tv_password = (TextView)findViewById(R.id.password);
edit_name = (EditText)findViewById(R.id.Ename);
edit_passwprd = (EditText)findViewById(R.id.Epassword);
stratButton = (Button)findViewById(R.id.login);
cancelButton = (Button)findViewById(R.id.cancel);
checkBox = (CheckBox)findViewById(R.id.checkbox);
sharedPre