我用sharepreferences写了一个简单的记住密码和账号
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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="zking.com.ass.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名:"
android:id="@+id/yhm_name"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码:"
android:id="@+id/qrr_pass"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存密码"
android:id="@+id/jizhumima"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:onClick="login"
/>
</LinearLayout>
得到sharepreferences (文件,xml–>键值对Map)
Context.MODE_PRIVATE是默认模式,是私有的只能被本身访问,在这种模式下原来的数据会被新写入的数据替代。
SharedPreferences sp= getSharedPreferences("loginfo", Context.MODE_PRIVATE);
ed = sp.edit();
//取数据 然后赋值到yhm_name
String name=sp.getString("name","");
yhm_name.setText(name);
//这里的就是说如果你点击了记住密码 在登录的话信息就会记住
boolean aa=sp.getBoolean("isRemember",false);
if (aa){
String pass=sp.getString("pass","");
qrr_pass.setText(pass);
}
jizhumima.setChecked(aa);
下面的代码就是说你点击的登录就会触发一个方法吧信息存入sharepreferences
public void login(View view){
//获取用户名密码
String name=yhm_name.getText().toString();
String pwd=qrr_pass.getText().toString();
//判断是否记住密码
if (jizhumima.isChecked()){
//存()
ed.putString("name",name);
ed.putString("pass",pwd);
ed.putBoolean("isRemember",true);
}
else{
//不存(只记住账号)
ed.putString("name",name);
ed.putBoolean("isRemember",false);
}
ed.commit();
}
这个是点击登录后的效果
效果图如下: