activity_main.xml MainActivity.java package com.example.sharedpreferencesdemo;import android.content.SharedPreferences;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.text.TextUtils;import android.vie
MainActivity.java
package com.example.sharedpreferencesdemo; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText name, pwd; private CheckBox check; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = (EditText) findViewById(R.id.name); pwd = (EditText) findViewById(R.id.pwd); check = (CheckBox) findViewById(R.id.check); //1。通过getSharedPreferences获得一个sp对象 sp = getSharedPreferences("inclogin", 0); String n1 = sp.getString("name", ""); String p1 = sp.getString("pwd", ""); name.setText(n1); pwd.setText(p1); } public void click(View view) { String n = name.getText().toString().trim(); String p = pwd.getText().toString().trim(); if (TextUtils.isEmpty(name.getText().toString().trim()) || TextUtils.isEmpty(pwd.getText().toString().trim())) { Toast.makeText(MainActivity.this, "账号密码不能为空", Toast.LENGTH_SHORT).show(); } else { if (check.isChecked()) { //2.获取sp的编辑器 SharedPreferences.Editor edit = sp.edit(); edit.putString("name", n); edit.putString("pwd", p); edit.commit(); }else{ } Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show(); } } }