当前位置:主页 > 移动开发 > Android代码 >

Android sharedPreferences实现记住密码功能

时间:2021-07-12 13:29:31 | 栏目:Android代码 | 点击:

实现记住密码功能,供大家参考,具体内容如下

编写界面交互代码:

package com.example.bz0209.login;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
  private EditText username;
  private EditText password;
  private CheckBox ck;
  private SharedPreferences sharedPreferences;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    sharedPreferences=getSharedPreferences("remeberword",MODE_PRIVATE);
    Boolean isRemeber=sharedPreferences.getBoolean("remeberword",false);
    if(isRemeber) {
      String name=sharedPreferences.getString("name","");
      String pass=sharedPreferences.getString("pass","");
      username.setText(name);
      password.setText(pass);
      ck.setChecked(true);
    }
  }
  private void initView(){
    username=(EditText)findViewById(R.id.username);
    password=(EditText)findViewById(R.id.password);
    ck= (CheckBox) findViewById(R.id.ck);
  }
  private void login(View view){//在layout中设置onClick事件
    String name=username.getText().toString();
    String pass=password.getText().toString();
    if("admin".equals(name)&&"123".equals(pass)){
     SharedPreferences.Editor editor=sharedPreferences.edit();
      if(ck.isChecked()){
        editor.putBoolean("remeberword",true);
        editor.putString("name",name);
        editor.putString("pass",pass);
      }else{
        editor.clear();
      }
      editor.commit();
    }
  }
}

您可能感兴趣的文章:

相关文章