学习了sharedpreferences之后 利用sharedpreferences实现一个都记住密码的登录案例
一 .何为sharedpreferences
1.使用键值对的方式来存储数据
2.支持多种不同数据类型的存储
获取SharedPreferences对象
方式一:Context类只能够的getSharedPreferences()方法
方法中的参数
第一个参数:指定文件的名称,若指定文件不存在则创建一个
第二个参数:制定操作模式 MODE_PRIVATE 和MODE_MULTI_PROCESS
MODE_PRIVATE 和直接传入0效果是相同的,表示只有当前的应用程序才可以对这个
SharedPreference进行读写。
MODE_MULTI_PROCESS 则用于有多个进程中对同一个SharedPreference文件进行读写的情况
注意: MODE_WORLD_READALBE和MODE_WORLD_WRITEABLE这两种模式已在Android4.2版本中被废弃
方式二:Activity类中的getPreferencrs()方法
该方法只接受一个操作模式参数,因为使用这个方法时会自动将当前活动的类名作为
SharedPreference的文件名
· 方式三:PreferenceManager类中的getDefaultSharedPreferences()方法
这是一个静态方法,只接受一个参数(Comtext(上下文)),并自动使用当前程序的包名作为前缀来命名SharedPreference文件
使用SharedPreferences存储数据
1.调用SharedPreference对象的edit()方法来获得SharedPreferences.Editor对象
2.向SharedPreferences.Editor添加数据
3.调用Commit()方法将添加的数据提交,从而完成数据存储操作
使用SharedPreferences读取数据
SharedPreference对象提供了一系列的get方法
第一个参数是键,传入存储数据时使用的键就可以得到相应的值
第二个参数时默认值,当传入的键找不到对应的值时,会以什么样的默认值进行返回。
二、实现过程
1.登陆界面的实现
登录界面分两部分:上部界面和下半部分
上半部代码
<?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="wrap_content"
android:background="@drawable/beijing"
>
/*此处为自定义的ImageVIew*/
<bzu.edu.cn.login.View.RoundImageView
android:id="@+id/v1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:src="@drawable/default_nor_avatar"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="20dp"
android:layout_below="@+id/user"
android:background="@drawable/yuanjiao"
android:hint="密码"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="20dp"
android:inputType="textPassword"
/>
<EditText
android:id="@+id/user"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="账号"
android:layout_marginTop="20dp"
android:background="@drawable/yuanjiao"
android:layout_below="@+id/v1"
android:layout_alignLeft="@+id/password"
android:layout_alignStart="@+id/password"
android:layout_alignRight="@+id/password"
android:layout_alignEnd="@+id/password" />
</RelativeLayout>
下半部代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
tools:context="bzu.edu.cn.login.LoginActivity"
android:background="@drawable/loginb"
>
<include
layout="@layout/login_top"
android:id="@+id/top"
>
</include>
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="确认登录"
android:textColor="@color/bai"
android:background="@drawable/button"
android:layout_marginTop="66dp"
android:layout_below="@+id/top"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="login"
/>
<CheckBox
android:id="@+id/c1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"
android:layout_marginLeft="23dp"
android:layout_marginStart="23dp"
android:layout_below="@+id/top"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
完成之后的界面
loginActivvity.java
package bzu.edu.cn.login;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private EditText etNumber;
private EditText etPassword;
private CheckBox checkBox;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_main);
initView();
sp=getSharedPreferences("data",MODE_PRIVATE);
boolean isRemcmber=sp.getBoolean("data",false);
if((isRemcmber)){
String name = sp.getString("name","'");
String password =sp.getString("password","");
etNumber.setText(name);
etPassword.setText(password);
checkBox.setChecked(true);
}
}
private void initView()
{
etNumber=(EditText)findViewById(R.id.user);
etPassword=(EditText)findViewById(R.id.password);
checkBox =(CheckBox)findViewById(R.id.c1);
}
public void login(View view) {
String name = etNumber.getText().toString();
String password = etPassword.getText().toString();
if ("admin".equals(name) && "123456".equals(password))
{
SharedPreferences.Editor editor = sp.edit();
if (checkBox.isChecked()) {
editor.putBoolean("data", true);
editor.putString("name", name);
editor.putString("password", password);
} else {
editor.clear();
}
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
} else{
Toast.makeText(this, "账号或密码有误", Toast.LENGTH_LONG).show();
}
}
}
下面是自定义ImageView的代码
1.创建一个RoundImageView.java类
package bzu.edu.cn.login.View;
/**
* Created by 刘平鲁 on 2017/4/12.
*/
import bzu.edu.cn.login.R;
import bzu.edu.cn.login.View.RoundImageView;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;
public class RoundImageView extends ImageView {
// ImageView类型
private int type;
// 圆形图片
private static final int TYPE_CIRCLE = 0;
// 圆角图片
private static final int TYPE_ROUND = 1;
// 默认圆角宽度
private static final int BORDER_RADIUS_DEFAULT = 10;
// 获取圆角宽度
private int mBorderRadius;
// 画笔
private Paint mPaint;
// 半径
private int mRadius;
// 缩放矩阵
private Matrix mMatrix;
// 渲染器,使用图片填充形状
private BitmapShader mBitmapShader;
// 宽度
private int mWidth;
// 圆角范围
private RectF mRectF;
public RoundImageView(Context context) {
this(context, null);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// 初始化画笔等属性
mMatrix = new Matrix();
mPaint = new Paint();
mPaint.setAntiAlias(true);
// 获取自定义属性值
TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RoundImageView, defStyle, 0);
int count = array.getIndexCount();
for (int i = 0; i < count; i++) {
int attr = array.getIndex(i);
switch (attr) {
case R.styleable.RoundImageView_borderRadius:
// 获取圆角大小
mBorderRadius = array.getDimensionPixelSize(R.styleable.RoundImageView_borderRadius, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, BORDER_RADIUS_DEFAULT, getResources().getDisplayMetrics()));
break;
case R.styleable.RoundImageView_imageType:
// 获取ImageView的类型
type = array.getInt(R.styleable.RoundImageView_imageType, TYPE_CIRCLE);
break;
}
}
// Give back a previously retrieved StyledAttributes, for later re-use.
array.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 如果是圆形,则强制宽高一致,以最小的值为准
if (type == TYPE_CIRCLE) {
mWidth = Math.min(getMeasuredWidth(), getMeasuredHeight());
mRadius = mWidth / 2;
setMeasuredDimension(mWidth, mWidth);
}
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) {
return;
}
// 设置渲染器
setShader();
if (type == TYPE_ROUND) {
canvas.drawRoundRect(mRectF, mBorderRadius, mBorderRadius, mPaint);
} else {
canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);
}
}
private void setShader() {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
Bitmap bitmap = drawable2Bitmap(drawable);
mBitmapShader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
float scale = 1.0f;
if (type == TYPE_ROUND) {
scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(), getHeight() * 1.0f / bitmap.getHeight());
} else if (type == TYPE_CIRCLE) {
// 取小值,如果取大值的话,则不能覆盖view
int bitmapWidth = Math.min(bitmap.getWidth(), getHeight());
scale = mWidth * 1.0f / bitmapWidth;
}
mMatrix.setScale(scale, scale);
mBitmapShader.setLocalMatrix(mMatrix);
mPaint.setShader(mBitmapShader);
}
/**
* 将Drawable转化为Bitmap
*
* @param drawable
* @return
*/
private Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) drawable;
return bd.getBitmap();
}
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 创建画布
Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
drawable.draw(canvas);
return bitmap;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mRectF = new RectF(0, 0, getWidth(), getHeight());
}
/**
* 对外公布的设置borderRadius方法
*
* @param borderRadius
*/
public void setBorderRadius(int borderRadius) {
int pxValue = dp2px(borderRadius);
if (this.mBorderRadius != pxValue) {
this.mBorderRadius = pxValue;
// 这时候不需要父布局的onLayout,所以只需要调用onDraw即可
invalidate();
}
}
/**
* 对外公布的设置形状的方法
*
* @param type
*/
public void setType(int type) {
if (this.type != type) {
this.type = type;
if (this.type != TYPE_CIRCLE && this.type != TYPE_ROUND) {
this.type = TYPE_CIRCLE;
}
// 这个时候改变形状了,就需要调用父布局的onLayout,那么此view的onMeasure方法也会被调用
requestLayout();
}
}
/**
* dp2px
*/
public int dp2px(int val) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, val, getResources().getDisplayMetrics());
}
}
调用该ImageView是直接通过包名—类名引用就可以了
还有一些样式文件如图
beijing.xml代码如下
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#00000000" />
<corners android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp" android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
button,xml代码
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 填充的颜色:这里设置背景透明 -->
<solid android:color="@android:color/transparent" />
<!-- 边框的颜色 :不能和窗口背景色一样-->
<stroke
android:width="3dp"
android:color="#00000000" />
<!-- 设置按钮的四个角为弧形 -->
<!-- android:radius 弧形的半径 -->
<corners android:radius="5dip" />
<!-- padding:Button里面的文字与Button边界的间隔 -->
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
yuanjiao.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#FFFFFF" />
<corners android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp" android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
运行结果
第一次运行图
输入密码登陆之后
记住密码并且退出之后
输入密码错误时
到这里就基本完成了