編輯:關於 Android 程式設計
SharedPreferences 提供開發者保存與讀取基本資料類型鍵值對的能力,主要用於 boolean、float、int、long 與 String 等基本類型。它的資料以 XML 檔案形式存在本地,位置在 /data/data/包名/shared_prefs 目錄下。應用結束後資料仍會保留,只要程式沒有被解除安裝,下次啟動時還能存取上次保存的資料。
SharedPreferences 物件並非用 new 建立,而是透過 getSharedPreferences(String name, int mode) 方法取得。這個方法是 Context 提供的,第一個參數是共享檔案的名稱,第二個參數是資料保存的模式。對於以同一檔名取得的多個 SharedPreferences 參照,它們指向的是同一個物件。
從 SharedPreferences 物件取值時,主要用該類別定義的 getXxx() 方法,例如:
String name = share.getString("name", "");
edit() 方法,取得 SharedPreferences.Editor 參照。putBoolean()、putString() 等方法寫入值。commit() 方法提交新值。程式功能:
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/main_et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleline="true"
android:hint="請輸入用戶名" />
<EditText
android:id="@+id/main_et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleline="true"
android:hint="密碼" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<CheckBox
android:id="@+id/main_cb_remember"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="記住密碼" />
<CheckBox
android:id="@+id/main_cb_auto"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="自動登入" />
</LinearLayout>
<TextView
android:id="@+id/main_tv_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#336699"
android:gravity="center"
android:padding="10dp"
android:text="登入"
android:textColor="@android:color/white" />
</LinearLayout>
為了讓資料存取更簡潔,我們封裝一個 SPHelper 工具類,透過 ContentValue 一次處理多筆資料:
package com.lwz.sharepreferences;
import android.content.Context;
import android.content.SharedPreferences;
/**
* SharePreference 工具類,用它可以更方便地進行簡單資料儲存。
* 1. 透過建構方法傳入上下文與檔名
* 2. 透過 putValues 傳入一或多個自訂的 ContentValue 物件進行儲存
* 3. 透過 get 方法讀取資料
* 4. 透過 clear 方法清除這個檔案的所有資料
*/
public class SPHelper {
SharedPreferences sharedPreferences;
// 透過建構方法傳入上下文與檔名
SPHelper(Context context, String fileName) {
// 使用 getSharedPreferences 而非 new 建立
sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
}
// 用來承載 key 與 value 的內部類
static class ContentValue {
String key;
Object value;
ContentValue(String key, Object value) {
this.key = key;
this.value = value;
}
}
// 一次可傳入多個 ContentValue
public void putValues(ContentValue... contentValues) {
SharedPreferences.Editor editor = sharedPreferences.edit();
for (ContentValue contentValue : contentValues) {
if (contentValue.value instanceof String) {
editor.putString(contentValue.key, contentValue.value.toString()).commit();
}
if (contentValue.value instanceof Integer) {
editor.putInt(contentValue.key, Integer.parseInt(contentValue.value.toString())).commit();
}
if (contentValue.value instanceof Long) {
editor.putLong(contentValue.key, Long.parseLong(contentValue.value.toString())).commit();
}
if (contentValue.value instanceof Boolean) {
editor.putBoolean(contentValue.key, Boolean.parseBoolean(contentValue.value.toString())).commit();
}
}
}
public String getString(String key) {
return sharedPreferences.getString(key, null);
}
public boolean getBoolean(String key) {
return sharedPreferences.getBoolean(key, false);
}
public int getInt(String key) {
return sharedPreferences.getInt(key, -1);
}
public long getLong(String key) {
return sharedPreferences.getLong(key, -1);
}
// 清除目前檔案的所有資料
public void clear() {
sharedPreferences.edit().clear().commit();
}
}
package com.lwz.sharepreferences;
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.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
EditText et_username;
EditText et_password;
CheckBox cb_remenber;
CheckBox cb_auto;
TextView tv_login;
boolean isAutoLogin = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
idFirstlogin(); // 判斷是否第一次登入
initView(); // 初始化頁面資料
}
private void initView() {
et_username = (EditText) findViewById(R.id.main_et_username);
et_password = (EditText) findViewById(R.id.main_et_password);
cb_remenber = (CheckBox) findViewById(R.id.main_cb_remember);
cb_auto = (CheckBox) findViewById(R.id.main_cb_auto);
tv_login = (TextView) findViewById(R.id.main_tv_login);
tv_login.setOnClickListener(this);
cb_remenber.setOnCheckedChangeListener(this);
cb_auto.setOnCheckedChangeListener(this);
SPHelper helper = new SPHelper(this, "login");
isAutoLogin = helper.getBoolean("isAutoLogin");
String name = helper.getString("username");
String pass = helper.getString("password");
if (!TextUtils.isEmpty(name)) {
et_username.setText(name);
et_password.setText(pass);
cb_remenber.setChecked(true);
}
if (isAutoLogin) {
Toast.makeText(this, name + " 自動登入中……", Toast.LENGTH_LONG).show();
cb_auto.setChecked(true);
}
}
private void idFirstlogin() {
SharedPreferences sp = getSharedPreferences("set", MODE_PRIVATE);
boolean isfirst = sp.getBoolean("isfirst", true);
if (isfirst) {
SharedPreferences.Editor et = sp.edit();
et.putBoolean("isfirst", false);
et.commit();
Toast.makeText(this, "第一次登入", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onClick(View v) {
String[] name = {"李文志", "李世民", "李嘉誠", "lili"};
String username = et_username.getText().toString();
String password = et_password.getText().toString();
if (TextUtils.isEmpty(username)) {
Toast.makeText(this, "用戶名不能為空", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "密碼不能為空", Toast.LENGTH_SHORT).show();
return;
}
boolean isrightname = false;
for (int i = 0; i < name.length; i++) {
if (username.equals(name[i]) && password.equals("123456")) {
Toast.makeText(this, "恭喜你登入成功", Toast.LENGTH_LONG).show();
isrightname = true;
SPHelper helper = new SPHelper(this, "login");
if (cb_remenber.isChecked()) {
helper.putValues(new SPHelper.ContentValue("username", username));
helper.putValues(new SPHelper.ContentValue("password", password));
} else {
helper.clear();
}
if (cb_auto.isChecked()) {
helper.putValues(new SPHelper.ContentValue("isAutoLogin", true));
} else {
helper.putValues(new SPHelper.ContentValue("isAutoLogin", false));
}
}
}
if (!isrightname) {
Toast.makeText(this, "用戶名或密碼不正確!", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView == cb_remenber) {
if (!isChecked) {
cb_auto.setChecked(false); // 取消記住密碼時,自動登入也取消
}
}
if (buttonView == cb_auto) {
if (isChecked) {
cb_remenber.setChecked(true); // 勾選自動登入時,記住密碼也自動勾選
}
}
}
}
SharedPreferences 適合保存少量、簡單的鍵值型資料,用它來記錄登入狀態、使用者偏好等相當合適。這個範例尚未實作多帳號登入(如 QQ 那樣的帳號切換),若想做到那種效果,可以考慮用 ExpandableListView 的下拉清單來顯示曾登入過的帳號。
Android View 系統解析:繪制流程與自定義
本文聚焦 Android View 系統的下半部分,說明繪製流程、MeasureSpec 與自定義 View 的關鍵概念。ViewRoot 與 DecorViewView
Android ProgressBar 客製化:旋轉動畫與自訂水平進度條
ProgressBar 是少數「預設樣式很醜、但客製化很簡單」的元件。本文示範兩種常見需求:換掉那個轉圈圈的小動畫,以及做出一條自訂配色的水平進度條。 一、自訂旋轉類型的
Android 自訂帶圖示的 EditText:可點擊的右側按鈕元件
前言 最近做登入模組時,需要一個右側帶圖示、而且圖示可以點擊的 EditText(例如「顯示/隱藏密碼」)。查了資料之後自己包了一個自訂元件,之後專案各處都能重複使用,記
Android 浮動視圖實作:跟手拖曳並自動貼邊的互動效果
浮動式 View 常見於懸浮按鈕、客服入口或快捷操作。要實作跟隨手指拖動並自動貼邊的效果,可以讓自訂 View 繼承 ImageView,並在 onTouch 中處理 A