<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:padding="20dp"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<EditText
android:id="@+id/name_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名"/>
<EditText
android:id="@+id/pass_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"/>
</LinearLayout>
<Button
android:id="@+id/bt"
android:text="登录"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
public class MainActivity2 extends AppCompatActivity {
private EditText name_et,pass_et;
private CheckBox cb;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
name_et=findViewById(R.id.name_et);
pass_et=findViewById(R.id.pass_et);
cb=findViewById(R.id.cb);
bt=findViewById(R.id.bt);
SharedPreferences sharedPreferences = getSharedPreferences("sp", MODE_PRIVATE);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = name_et.getText().toString().trim();
String pass = pass_et.getText().toString().trim();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)){
Toast.makeText(MainActivity2.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
}else{
if (cb.isChecked()){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name",name);
editor.putString("pass",pass);
editor.putBoolean("rememberPass",true);
editor.apply();
}
Intent intent = new Intent(MainActivity2.this, MainActivity3.class);
startActivity(intent);
}
}
});
boolean rememberPass = sharedPreferences.getBoolean("rememberPass", false);
if (rememberPass){
name_et.setText(sharedPreferences.getString("name",""));
pass_et.setText(sharedPreferences.getString("pass",""));
cb.setChecked(true);
}
}
}