package com.example.app3;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText text1;
private EditText text2;
private CheckBox cb;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (EditText) findViewById(R.id.text1);
text2 = (EditText) findViewById(R.id.text2);
cb = (CheckBox) findViewById(R.id.cb);
bt = (Button) findViewById(R.id.bt);
final SharedPreferences login = getSharedPreferences("login",MODE_PRIVATE);
boolean isCheck = login.getBoolean("isCheck", false);
if (isCheck){
String name = login.getString("name","");
text1.setText(name);
String pwd = login.getString("pwd","");
text2.setText(pwd);
}
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (cb.isChecked()){
String s = text1.getText().toString();
String s1 = text2.getText().toString();
SharedPreferences login = getSharedPreferences("login", MODE_PRIVATE);
SharedPreferences.Editor edit = login.edit();
edit.putString("name",s);
edit.putString("pwd",s1);
edit.putBoolean("isCheck",true);
edit.apply();
}else{
SharedPreferences login1 = getSharedPreferences("login", MODE_PRIVATE);
SharedPreferences.Editor edit = login1.edit();
edit.clear();
edit.apply();
}
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="123"
/>
<EditText
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="321"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/cb"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt"
android:text="bb"
/>
</LinearLayout>