一、布局
1.布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="账号:"
android:textSize="30dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入账号"
android:textSize="30dp"
android:id="@+id/etname"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码:"
android:textSize="30dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:textSize="30dp"
android:id="@+id/etpsw"/>
</LinearLayout>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住账号和密码"
android:id="@+id/cb1"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="登录"
android:onClick="saveqq"/>
</LinearLayout>
2.布局界面
二、java代码
public class two extends AppCompatActivity {
EditText etname,etpsw;
CheckBox cb1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two);
etname= (EditText) findViewById(R.id.etname);
etpsw= (EditText) findViewById(R.id.etpsw);
cb1= (CheckBox) findViewById(R.id.cb1);
SharedPreferences sp=getSharedPreferences("data",MODE_PRIVATE);
//取值并判断
boolean isremember=sp.getBoolean("isremember",false);
if(isremember){
String name=sp.getString("name",null);
String psw =sp.getString("psw",null);
etname.setText(name);
etpsw.setText(psw);
}
}
public void saveqq(View V){
SharedPreferences sp= getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor ed= sp.edit();
//保存用户输入的用户名和密码
ed.putString("name",etname.getText().toString());
ed.putString("psw",etpsw.getText().toString());
//保存一个布尔类型的值用于记录用户是否选择记住密码
if(cb1.isChecked()){
ed.putBoolean("isremember",true);
}else{
ed.clear();
}
ed.commit();
Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
}
}