xml
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="姓名:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:layout_weight="1"
android:background="@drawable/edit_select"
android:hint="请输入姓名"
android:inputType="text"
android:maxLength="12"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_age"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="年龄:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_age"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:layout_weight="1"
android:background="@drawable/edit_select"
android:hint="请输入年龄"
android:inputType="number"
android:maxLength="2"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_height"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="身高:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_height"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:layout_weight="1"
android:background="@drawable/edit_select"
android:hint="请输入身高"
android:inputType="numberDecimal"
android:maxLength="5"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_weight"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="体重:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_weight"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:layout_weight="1"
android:background="@drawable/edit_select"
android:hint="请输入体重"
android:inputType="numberDecimal"
android:maxLength="5"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
<CheckBox
android:id="@+id/ck_married"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:gravity="center"
android:text="已婚"
android:textColor="@color/black"
android:textSize="17sp" />
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存到共享参数"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
Activity
java
package com.tiger.chapter06;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
public class ShareWriteActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_name;
private EditText et_age;
private EditText et_height;
private EditText et_weight;
private CheckBox ck_married;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_write);
et_name = findViewById(R.id.et_name);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
ck_married = findViewById(R.id.ck_married);
findViewById(R.id.btn_save).setOnClickListener(this);
//第一个参数取个名字 第二个参数 为我们这个 SharedPreferences 设置为私有 是在私有目录下 其他应用程序没法访问,只能当前这个应用程序访问
preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
reload();
}
private void reload() {
String name = preferences.getString("name", "");
et_name.setText(name);
int age = preferences.getInt("age", 0);
et_age.setText(String.valueOf(age));
float height = preferences.getFloat("height", 0f);
et_height.setText(String.valueOf(height));
float weight = preferences.getFloat("weight", 0f);
et_weight.setText(String.valueOf(weight));
boolean married = preferences.getBoolean("married", false);
ck_married.setChecked(married);
}
@Override
public void onClick(View v) {
String name = et_name.getText().toString();
String age = et_age.getText().toString();
String height = et_height.getText().toString();
String weight = et_weight.getText().toString();
//通过 SharedPreferences去编辑
//先获取它的 编辑器
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name",name);
editor.putInt("age",Integer.valueOf(age));
editor.putFloat("height",Float.valueOf(height));
editor.putFloat("weight",Float.valueOf(weight));
editor.putBoolean("married",ck_married.isChecked());
//提交
editor.commit();
}
}
记住密码
java
package com.tiger.chapter05;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.tiger.chapter05.util.ViewUtil;
import java.util.Random;
public class LoginMainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {
private TextView tv_password;
private EditText et_password;
private Button btn_forget;
private CheckBox ck_remember;
private EditText et_phone;
private RadioButton rb_password;
private RadioButton rb_verifycode;
private Button btn_login;
private ActivityResultLauncher<Intent> register;
private String verifyCode;
private String mPassword = "196852";
private SharedPreferences preferences;
private Boolean isRemember = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_main);
RadioGroup rg_login = findViewById(R.id.rg_login);
tv_password = findViewById(R.id.tv_password);
et_password = findViewById(R.id.et_password);
btn_forget = findViewById(R.id.btn_forget);
ck_remember = findViewById(R.id.ck_remember);
et_phone = findViewById(R.id.et_phone);
rb_password = findViewById(R.id.rb_password);
rb_verifycode = findViewById(R.id.rb_verifycode);
btn_login = findViewById(R.id.btn_login);
preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
reload();
register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
Intent data = result.getData();
if (data != null && result.getResultCode() == Activity.RESULT_OK) {
String newPassword = data.getStringExtra("new_password");
//用户密码已更改为新密码,故更新密码变量
mPassword = newPassword;
}
}
});
//给rg_login 设置单选监听器
rg_login.setOnCheckedChangeListener(this);
//主对象引用被垃圾回收,那么主对象里的子引用也会被垃圾回收
//给et_phone添加文本变更监听器
et_phone.addTextChangedListener(new HideTextWatcher(et_phone, 11));
et_password.addTextChangedListener(new HideTextWatcher(et_password, 6));
btn_forget.setOnClickListener(this);
btn_login.setOnClickListener(this);
}
private void reload() {
String phone = preferences.getString("phone", "");
et_phone.setText(phone);
String password = preferences.getString("password", "");
et_password.setText(password);
boolean isRemember = preferences.getBoolean("isRemember", false);
ck_remember.setChecked(isRemember);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.rb_password) {
//默认是密码被选中
//文本
tv_password.setText(getString(R.string.login_password));
//编辑框
et_password.setHint(getString(R.string.input_password));
//按钮
btn_forget.setText(getString(R.string.forget_password));
//将记住密码设置为不可见
ck_remember.setVisibility(View.VISIBLE);
} else {
//选择验证码登录
//文本
tv_password.setText(getString(R.string.verifycode));
//编辑框
et_password.setHint(getString(R.string.input_verifycode));
//按钮
btn_forget.setText(getString(R.string.get_verifycode));
//将记住密码设置为不可见
ck_remember.setVisibility(View.GONE);
}
}
@Override
public void onClick(View v) {
String phone = et_phone.getText().toString();
if (phone.length() < 11) {
Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_LONG).show();
return;
}
if (R.id.btn_forget == v.getId()) {
if (rb_password.isChecked()) {
//携带手机号码跳转到找回密码页面
Intent intent = new Intent(this, LoginForgetActivity.class);
intent.putExtra("phone", phone);
register.launch(intent);
} else {
//生成6位随机的验证码
verifyCode = String.format("%06d", new Random().nextInt(999999));
//以下弹出提醒对话框,提示用户记住六位验证码数字
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("请记住验证码");
builder.setMessage("手机号" + phone + ",本次验证码是" + verifyCode + ",请输入验证码");
builder.setPositiveButton("好的", null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
} else if (R.id.btn_login == v.getId()) {
if (rb_password.isChecked()) {
if (!mPassword.equals(et_password.getText().toString())) {
Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_LONG).show();
return;
}
if (ck_remember.isChecked()) {
}
//提示用户登录成功
loginSuccess(true);
} else {
if ("".equals(verifyCode)) {
Toast.makeText(this, "请先获取验证码", Toast.LENGTH_LONG).show();
return;
}
if (!verifyCode.equals(et_password.getText().toString())) {
Toast.makeText(this, "验证码不正确", Toast.LENGTH_LONG).show();
return;
}
//提示用户登录成功
loginSuccess(false);
verifyCode = "";
}
}
}
private void loginSuccess(boolean isPassword) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("登录成功");
builder.setMessage("手机号" + et_phone.getText().toString() + "登录成功了");
builder.setPositiveButton("确定返回", (dialog, which) -> {
finish();
});
builder.setNegativeButton("我在看看", null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
SharedPreferences.Editor editor = preferences.edit();
if (isPassword) {
if (ck_remember.isChecked()) {
editor.putString("phone", et_phone.getText().toString());
editor.putString("password", et_password.getText().toString());
editor.putBoolean("isRemember", ck_remember.isChecked());
editor.commit();
} else {
editor.clear();
editor.commit();
}
}else {
editor.putString("phone", et_phone.getText().toString());
editor.commit();
}
}
//定义一个编辑框监听器 在输入文本达到指定长度是自动隐藏输入法
private class HideTextWatcher implements TextWatcher {
private EditText mView;
private int maxLength;
public HideTextWatcher(EditText mView, int maxLength) {
this.mView = mView;
this.maxLength = maxLength;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
//获得已输入的文本字符串
String str = s.toString();
//输入文本达到11位 (如手机号码),或者达到6位 (如登录密码)时 关闭输入法
if (str.length() == maxLength) {
ViewUtil.hideOneInputMethod(LoginMainActivity.this, mView);
}
}
}
}