您的位置:首页 > Web前端

实践--使用SharedPreferences实现记住密码的功能

2016-03-27 19:50 429 查看
代码如下

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private Button button_login;
private CheckBox checkBox;
private EditText editText_account,editText_password;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
setOnListener();
SharedPreferences sharedPreferences=getSharedPreferences("mylogin",MODE_PRIVATE);
boolean isChecked=sharedPreferences.getBoolean("isChecked",false);
if (isChecked){
checkBox.setChecked(isChecked);
String account=sharedPreferences.getString("account","");
String password=sharedPreferences.getString("password","");
editText_account.setText(account);
editText_password.setText(password);
}
}

private void setOnListener() {
button_login.setOnClickListener(this);
}

private void init() {
button_login= (Button) findViewById(R.id.button_login);
checkBox= (CheckBox) findViewById(R.id.checkBox);
editText_account= (EditText) findViewById(R.id.editText_account);
editText_password= (EditText) findViewById(R.id.editText_password);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_login:
String account=editText_account.getText().toString();
String password=editText_password.getText().toString();
boolean isChecked=checkBox.isChecked();
if (TextUtils.isEmpty(account)){
Toast.makeText(MainActivity.this, "账号不能为空!!!", Toast.LENGTH_SHORT).show();
}else if(TextUtils.isEmpty(password)){
Toast.makeText(MainActivity.this, "密码不能为空!!!", Toast.LENGTH_SHORT).show();
}else{
SharedPreferences.Editor editor= (SharedPreferences.Editor) getSharedPreferences("mylogin",MODE_PRIVATE).edit();
editor.putString("account",account);
editor.putString("password",password);
editor.putBoolean("isChecked",isChecked);
editor.commit();
Toast.makeText(MainActivity.this, "存储成功!!!", Toast.LENGTH_SHORT).show();
}
break;
}
}
}


效果图如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: