public class MainActivity extends Activity {
private EditText e_name;
private EditText e_pass;
private Button but;
private CheckBox j_pass;
private CheckBox z_deng;
private SharedPreferences sharedPreferences;
private Editor edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
—–
记住密码,自动登录
//1找到控件
e_name = (EditText) findViewById(R.id.editText1);
e_pass = (EditText) findViewById(R.id.editText2);
but = (Button) findViewById(R.id.but01);
j_pass = (CheckBox) findViewById(R.id.j_pass);
z_deng = (CheckBox) findViewById(R.id.z_deng);
//2 得到sh
sharedPreferences = getSharedPreferences("User", MODE_PRIVATE);
//3 操作sh
edit = sharedPreferences.edit();
//5 取到记住密码的状态值
boolean j_ischeck = sharedPreferences.getBoolean("j_ischeck", false);
//8 取到自动登录的状态值
boolean z_ischeck = sharedPreferences.getBoolean("z_ischeck", false);
//9. 判断自动登录状态值 为true
if(z_ischeck){
//如果自动选中为选中就进入登陆
Intent intent =new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
finish();
}
//6 判断文件中记住密码的状态值
if(j_ischeck){
//如果为true通过key值得到name 和密码
String name2 = sharedPreferences.getString("name", null);
String pass2 = sharedPreferences.getString("pass", null);
//显示 勾选记住密码的复选框
j_pass.setChecked(true);
//设置值
e_name.setText(name2);
e_pass.setText(pass2);
}
//4 为but按钮设置监听
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//判断当前复选框是否是勾选状态,.默认判断true
if(j_pass.isChecked()){//如果勾选就存入一个为true的状态值,账户 密码
//得到输入框账号密码
String name1 = e_name.getText().toString();
String pass1 = e_pass.getText().toString();
//存入账户 密码 状态值
edit.putString("name", name1);
edit.putString("pass", pass1);
//存入文件中的状态值
edit.putBoolean("j_ischeck", true);
edit.commit();
}
//7 判断自动登录是否勾选 状态值为true
if(z_deng.isChecked()){
//存入状态值
edit.putBoolean("z_ischeck", true);
edit.commit();
}
Intent intent=new Intent (MainActivity.this,MainActivity2.class);
startActivity(intent);
finish();
}
});
}
}
—-注销—-
public class MainActivity2 extends Activity {
private Button but;
private SharedPreferences sharedPreferences;
private Editor edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//找到控件
but = (Button) findViewById(R.id.but02);
//得到
sharedPreferences = getSharedPreferences("User", MODE_PRIVATE);
edit = sharedPreferences.edit();
//为but设置店家监听 点击返回 清空
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//跳转时清空
edit.clear();
edit.commit();
Intent intent =new Intent(MainActivity2.this,MainActivity.class);
startActivity(intent);
finish();
}
});
}
}