开发步骤:
- 在程序布局中键入复选框
- 在LoginActivity类中加入登陆处理的方法
3.在 LoginActivity类中加入是否记住密码的判断方法
4.运用SharedPreferences进行用户名和密码的存储
5.如果用户名和密码正确,会跳转到欢迎界面
注意问题
- 要注意数据之间的转换
- 复选框的不同状态处理
- SharedPreferences的用法
- 页面的正确跳转
事件处理的主要代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences("userdata", Context.MODE_WORLD_READABLE);
Username = (EditText) findViewById(R.id.etUsername);
Password = (EditText) findViewById(R.id.etPassword);
cbPW =(CheckBox) findViewById(R.id.cbPW);
btnLogin = (Button) findViewById(R.id.btnLogin);
if(sp.getBoolean("IsCheck",true)){
//设置默认是记录密码状态
cbPW.setChecked(true);
Username.setText(sp.getString("UserName", ""));
Password.setText(sp.getString("Password", ""));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View view) {
UserNameValue = Username.getText().toString();
PasswordValue = Password.getText().toString();
if(UserNameValue.equals("admin")&&PasswordValue.equals("12345")){
Toast.makeText(LoginActivity.this,"登录成功", Toast.LENGTH_SHORT).show();
//登录成功和记住密码框为选中状态才保存用户信息
if(cbPW.isChecked())
{
//记住用户名、密码、
Editor editor = sp.edit();
editor.putString("UserName", UserNameValue);
editor.putString("Password",PasswordValue);
editor.commit();
}
//跳转界面
Intent intent = new Intent(LoginActivity.this,WelcomeAvtivity.class);
LoginActivity.this.startActivity(intent);
}else{
Toast.makeText(LoginActivity.this,"用户名或密码错误,请重新登录", Toast.LENGTH_LONG).show();
}
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (cbPW.isChecked()) {
System.out.println("记住密码已选中");
sp.edit().putBoolean("IsCheck", true).commit();
}else {
System.out.println("记住密码没有选中");
sp.edit().putBoolean("IsCheck", false).commit();
}
}