今天早上写了一个小demo 实现的是记住密码功能
用的是SharedPreferences存储
首先 SharePreferences是使用键值对来存储数据的并且她也支持多种不同数据类型的存储
具体用法
使用它先要获取到SharedPreferences的对象
得到对象的方式有三种
Context
得到对象之后
就可以开始了
1.调用edit获取一个SharedPreferences.Editor对象
2 像SharedPreferences。Editor对象中添加数据 put**()方法
3 调用commit()提交数据 完成存储
大概步骤就是这样 看一下主要的代码实现
package com.example.katherine_qj.remberpassword;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
/**
* Created by Katherine-qj on 2016/7/19.
*/
public class LoginActivity extends Activity {
private EditText username;
private EditText password;
private CheckBox checkBox;
private boolean isRemember;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private Button sign_in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
InitView();
if(isRemember){
/*将账号和密码都设置到文本框中
先得到在设置最后将选择框的状态改为选中状态*/
String account = preferences.getString("account","");
String pass = preferences.getString("pass","");
username.setText(account);
password.setText(pass);
checkBox.setChecked(true);
}
sign_in.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = username.getText().toString().trim();
String pass = password.getText().toString().trim();
if(account.equals("qinjie")&&pass.equals("123")){
editor=preferences.edit();
if(checkBox.isChecked()){
editor.putBoolean("remember_password",true);
editor.putString("account",account);
editor.putString("pass",pass);
}else {
editor.clear();
}
editor.commit();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
public void InitView(){
username = (EditText)findViewById(R.id.land_name);
password = (EditText)findViewById(R.id.land_password);
checkBox = (CheckBox)findViewById(R.id.checkbox);
sign_in=(Button)findViewById(R.id.button_sign_in);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
isRemember =preferences.getBoolean("remember_password",false);
}
}
github完整 demo下载地址
嗯 完成于政府办公室
好无聊