private EditText user_account_edit, user_pass_edit;
private SharedPreferences pref;
public SharedPreferences mSharedPreferences;
private CheckBox rememberPass;
onCreate()方法中:获取sp实例,调用 setRemember()方法,根据CheckBox 控件是否被选中进行判断,如果是选中,就从sp中取出用户名密码设置到界面上。点击登录按钮时,则调用 savedUsers()保存用户名密码到sp
findViewById(R.id.login_btn).setOnClickListener(this);
user_account_edit = (EditText) findViewById(R.id.user_account_edit);
user_pass_edit = (EditText) findViewById(R.id.user_pass_edit);
rememberPass = (CheckBox) findViewById(R.id.remember_pass);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setRemember();
/**
* 设置记住用户名和密码
*/
private void setRemember() {
if (isRemembered()) {
String nameFromLog = mSharedPreferences.getString("nameFromLog","");
String passFromLog = mSharedPreferences.getString("passFromLog","");
user_account_edit.setText(nameFromLog);
user_pass_edit.setText(passFromLog);
rememberPass.setChecked(true);
}
}
/**
* 获取记住密码的状态
*/
private boolean isRemembered() {
return mSharedPreferences.getBoolean("isRemembered",false);
}
/**
* 保存用户数据到Share
*/
private void savedUsers() {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("nameFromLog",user_account_edit.getText().toString().trim());
editor.putString("passFromLog",user_pass_edit.getText().toString().trim());
if (rememberPass.isChecked()) {
editor.putBoolean("isRemembered", true);
}else {
editor.putBoolean("isRemembered", false);
}
editor.commit();
}