1、activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/ed_username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Hello World!" />
<EditText
android:id="@+id/ed_passward"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Hello World!" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/cb_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:text="登录"/>
</LinearLayout>
</LinearLayout>
2、MainActivity.jave
package com.example.mysharedpreferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class MainActivity extends Activity implements View.OnClickListener{
private Button btn_login;
private CheckBox cb_box;
private EditText ed_username;
private EditText ed_passward;
//定义轻量级SharedPreferences存储器
private SharedPreferences config;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initupdate();
//存储文件名和模式,私有模式
config=getSharedPreferences("config",MODE_PRIVATE);
boolean ischeck=config.getBoolean("ischeck",false);
if (ischeck){
ed_username.setText(config.getString("username",""));
ed_passward.setText(config.getString("passward",""));
}
cb_box.setChecked(ischeck);
}
@Override
public void onClick(View v) {
//获取getSharedPreferences遍历器
SharedPreferences.Editor editor=config.edit();
//获取登录名和密码
String username=ed_username.getText().toString();
String passward=ed_passward.getText().toString();
boolean ischeck=cb_box.isChecked();
editor.putBoolean("ischeck",ischeck);
if (ischeck){
editor.putString("username",username).putString("passward",passward);
}else {
editor.remove("username").remove("passward");
}
//提交
editor.commit();
}
private void initupdate(){
btn_login=(Button)findViewById(R.id.btn_login);
cb_box=(CheckBox)findViewById(R.id.cb_box);
ed_username=(EditText)findViewById(R.id.ed_username);
ed_passward=(EditText)findViewById(R.id.ed_passward);
btn_login.setOnClickListener(this);
}
}