使用getSharedPreferences来设置
步骤1.在layout中设置一个checkbox
<CheckBox
android:id="@+id/chk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="记住我"
app:layout_constraintEnd_toEndOf="@+id/constraintLayout"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="@+id/constraintLayout"
app:layout_constraintTop_toBottomOf="@+id/constraintLayout" />
步骤2,在需要用到的activity中设置函数:
//新添加记住密码
public static void readFromPre(Context context, EditText tname, EditText tpass) {
SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo",context.MODE_PRIVATE);
String name = sharedPreferences.getString("name","");
String pass = sharedPreferences.getString("pass","");
tname.setText(name);
tpass.setText(pass);
}
public static void saveToPre(Context context, String name, String pass) {
SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo",context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name",name);
editor.putString("pass",pass);
editor.commit();
}
public static void deleteToPre(Context context){
SharedPreferences sharedPreferences=context.getSharedPreferences("userinfo",context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.clear();
editor.commit();
}
步骤3,在activity中初始化控件:
//记住密码
chk=(CheckBox)findViewById(R.id.chk);
readFromPre(this, edit_phonenum_pw, edit_password_pw);
if(!TextUtils.isEmpty(edit_phonenum_pw.getText().toString())){
chk.setChecked(true);
}
步骤4,在事件中设置
if (chk.isChecked())//如果选中了"记住我"的多选框,就将用户名和密码保存,否则不保存
{
String name = edit_phonenum_pw.getText().toString();
String password = edit_password_pw.getText().toString();
saveToPre(getBaseContext(), name, password);
}
else
deleteToPre(getBaseContext());