用安卓shareprences写一个账号密码登录界面,并保存密码账号,在下一次登录的时候进行校验
时间: 2024-04-29 12:26:15 浏览: 13
可以的,下面是一个简单的示例代码:
1.在XML布局文件中添加两个 EditText 控件(分别用于输入账号和密码)和一个 CheckBox 控件(用于保存密码)以及一个 Button 控件(用于登录):
```
<EditText
android:id="@+id/et_account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="账号" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"
android:inputType="textPassword" />
<CheckBox
android:id="@+id/cb_save_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码" />
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录" />
```
2. 在 Java 代码中获取 EditText 和 CheckBox 控件的实例,并为 Button 控件设置点击事件:
```
SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
final SharedPreferences.Editor editor = sp.edit();
final EditText etAccount = findViewById(R.id.et_account);
final EditText etPassword = findViewById(R.id.et_password);
final CheckBox cbSavePassword = findViewById(R.id.cb_save_password);
Button btnLogin = findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = etAccount.getText().toString().trim();
String password = etPassword.getText().toString().trim();
boolean savePassword = cbSavePassword.isChecked();
// 判断账号和密码是否为空
if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "账号或密码不能为空", Toast.LENGTH_SHORT).show();
return;
}
// 登录校验
if (account.equals("admin") && password.equals("123456")) {
Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
// 保存密码
if (savePassword) {
editor.putString("account", account);
editor.putString("password", password);
editor.apply();
} else {
editor.remove("account");
editor.remove("password");
editor.apply();
}
// TODO: 登录成功后的逻辑
} else {
Toast.makeText(getApplicationContext(), "账号或密码错误", Toast.LENGTH_SHORT).show();
}
}
});
// 自动填充保存的账号和密码
String account = sp.getString("account", "");
String password = sp.getString("password", "");
etAccount.setText(account);
etPassword.setText(password);
cbSavePassword.setChecked(!TextUtils.isEmpty(password));
```
这段代码中,我们使用了 Android 中的 SharedPreferences 来保存和读取账号和密码。其中,通过调用 editor.putString() 方法来保存账号和密码,通过调用 editor.remove() 方法来删除之前保存的账号和密码。在登录时,我们首先判断账号和密码是否为空,然后再进行登录校验。最后将输入框中的账号和密码保存到 SharedPreferences 中。在每次启动应用时,我们会自动填充保存的账号和密码到输入框中。