数据存储:SharePreferences
public class MainActivity extends AppCompatActivity{
EditText useName, password;
Button button1, button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
useName = findViewById(R.id.useName);
password = findViewById(R.id.password);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
SharedPreferences preferences = getSharedPreferences("myShared", MODE_PRIVATE);
String account = preferences.getString("account", "");
String pwd = preferences.getString("pwd", "");
useName.setText(account);
password.setText(pwd);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tempAcc = useName.getText().toString();
String tempPwd = password.getText().toString();
SharedPreferences.Editor edit = preferences.edit();
edit.putString("account", tempAcc);
edit.putString("pwd", tempPwd);
edit.commit();
Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor edit = preferences.edit();
edit.remove("account");
edit.remove("pwd");
edit.commit();
useName.setText(
preferences.getString("account", "")
);
password.setText(
preferences.getString("pwd", "")
);
Toast.makeText(MainActivity.this, "清除成功", Toast.LENGTH_SHORT).show();
}
});
}
}
界面效果图
