package com.zdsoft.sharedpreferces1207;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText et_user, et_password;
private CheckBox cb_remember;
private final String INFO = "info";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
read();
}
@Override
protected void onPause() {
super.onPause();
write();
}
//实例化控件
private void initView() {
et_user = (EditText) findViewById(R.id.et_user);
et_password = (EditText) findViewById(R.id.et_password);
cb_remember = (CheckBox) findViewById(R.id.cb_remember);
}
//文件写入
private void write() {
//获得SharedPreferences对象
SharedPreferences sharedPreferences = getSharedPreferences(INFO, Context.MODE_PRIVATE);
//获得SharedPreferences.Editor对象
SharedPreferences.Editor editor = sharedPreferences.edit();
if (cb_remember.isChecked()) {
editor.putString("user", et_user.getText().toString());
editor.putString("password", et_password.getText().toString());
editor.putBoolean("checked", cb_remember.isChecked());
} else {
editor.putString("user", "");
editor.putString("password", "");
editor.putBoolean("checked", false);
}
editor.commit();
}
//文件读取
private void read() {
SharedPreferences sharedPreferences = getSharedPreferences(INFO, Context.MODE_PRIVATE);
String user = sharedPreferences.getString("user", "");
String password = sharedPreferences.getString("password", "");
boolean checked = sharedPreferences.getBoolean("checked", false);
et_user.setText(user);
et_password.setText(password);
cb_remember.setChecked(checked);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户名:" />
<EditText
android:id="@+id/et_user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码:" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword" />
</LinearLayout>
<CheckBox
android:id="@+id/cb_remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住用户名及密码" />
</LinearLayout>