上篇文章我们学习编写了一个简单的登录页面,本篇文章,我们继续丰富这个页面,实现自动登录和记住用户名密码,学习安卓一个简单的数据存储器SharedPreferences使用。
SharedPreferences
SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个基于XML文件存储key-value(键值对)。SharedPreferences常用来存储一些轻量级的数据. 其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。
初始化
spUser = this.getSharedPreferences(spName, Context.MODE_PRIVATE);
获取键值对
spUser.getString(spKeyUser, "")
设置键值对
SharedPreferences.Editor editor = spUser.edit();
editor.putString(spKeyUser, userid);
editor.putString(spKeyPass,pass);
editor.commit();
登录页面
增加记住用户名密码,自动登录多选框
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#2197db"
>
<TextView
android:text="XS-TestApp"
android:id="@+id/loginbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="90dp"
android:layout_marginBottom="20dp"
android:textColor="#fffefe"
android:textSize="30sp"/>
<LinearLayout
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/loginbutton"
android:layout_marginLeft="28dp"
android:layout_marginRight="28dp"
android:background="#fff"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="44dp"
android:background="#fff"
android:gravity="center_vertical"
android:orientation="horizontal" >
<EditText
android:id="@+id/userId"
android:layout_width=