學習了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 = ;
// 圓角圖檔
private static final int TYPE_ROUND = ;
// 預設圓角寬度
private static final int BORDER_RADIUS_DEFAULT = ;
// 擷取圓角寬度
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, );
}
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, );
int count = array.getIndexCount();
for (int i = ; 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 / ;
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 = f;
if (type == TYPE_ROUND) {
scale = Math.max(getWidth() * f / bitmap.getWidth(), getHeight() * f / bitmap.getHeight());
} else if (type == TYPE_CIRCLE) {
// 取小值,如果取大值的話,則不能覆寫view
int bitmapWidth = Math.min(bitmap.getWidth(), getHeight());
scale = mWidth * f / 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(, , 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(, , 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>
運作結果
第一次運作圖
輸入密碼登陸之後
記住密碼并且退出之後
輸入密碼錯誤時
到這裡就基本完成了