小记
笔记
基于之前做的登录功能,现在通过SharedPrefences实现记住密码功能
先梳理一下SharedPrefences的基本操作:
添加存储信息:
1、先获取SharePrefence对象
获取SharePrefence的三种方式:
Context的getSharedPreferences方法 两个参数:文件名、操作模式:MODE_PRIVATE
Activity的getPreferences方法
PreferenceManager的getDefaultSharedPrefences方法
2、调用edit()来获取一个Editor对象
前两步可以整合为一步完成
3、添加数据putStirng()、putBoolean()
4、提交editor.apply()
提取查询信息:
前两步相同
3、getString()、getBoolean()
getString("name","张三");键值对的形式,第二个参数是默认
大致就这些东西
下面整合到之前的登录页面上去
xml添加一个单选框
<?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:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:hint="请输入用户名"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/account"/>
<EditText
android:hint="请输入密码"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/password"
android:inputType="textPassword"/>
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_login"
android:text="登录"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn_relogin"
android:text="强制登录"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"
android:id="@+id/checkbox_remeber_pass"
/>
</LinearLayout>
单选框注册,在登录按钮添加如下功能:
当点击登录按钮,先通过SharedPreferences找一下remember_password是否为true,为true则填充信息,为false则进行下一步
判断用户名密码是否正确,判断记住密码是否选择。
记住密码选择则通过SharedPreferences添加信息,remember_password设置为true
代码如下:
String account=et_account.getText().toString();
String password=et_password.getText().toString();
if (account.equals("admin")&&password.equals("123456")) {
editor = pref.edit();
if (checkbox_remberpass.isChecked()) {
Log.d(TAG, "check_real: 选择了记住密码");
editor.putBoolean("remember_password", true);
editor.putString("account", account);
editor.putString("password", password);
} else {
editor.clear();
}
editor.apply();
Toast.makeText(this, "用户名:" + account + "密码:" + password, Toast.LENGTH_SHORT).show();
}