android中记住密码设置

使用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());



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值