編輯:關於 Android 程式設計
SharedPreferences 是 Android 中最輕量的本地資料持久化解決方案,用來保存鍵值對形式的簡單設定資料。它上手門檻低、邏輯清晰,非常適合初學者理解「資料如何跨啟動被保留」這件事。本文就以一個經典的「記住密碼」登入範例為主線,把讀取與寫入的流程完整走一遍,最後附上全部原始碼。
先看效果:在登入介面輸入帳號 admin、密碼 123,並勾選「記住密碼」後登入。

登入成功後會直接跳轉到下一個頁面。此時若把 App 關掉再重新開啟,你會發現帳號與密碼已經被自動填回,勾選框也處於選取狀態。
反過來,如果密碼輸入錯誤,或者登入時沒有勾選「記住密碼」,程式會把 SharedPreferences 中儲存的資料清空,於是下次登入時 EditText 又是空白的。

理解兩個核心角色就足夠了:SharedPreferences 負責讀取資料,而 SharedPreferences.Editor 負責寫入與提交資料。關鍵在於——所有透過 editor 加入的內容,最後一定要呼叫 commit() 才會真正落地。
MainActivity:
import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; 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 MainActivity extends Activity { //使用SharedPreferences進行讀取 private SharedPreferences pref; //使用SharedPreferences.Editor進行存儲 private SharedPreferences.Editor editor; private Button button; private CheckBox checkbox; private EditText accountEdit; private EditText passwordEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //取消標題 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); //制定SharedPreference的文件名為data pref= getSharedPreferences("data",MODE_PRIVATE); editor=pref.edit(); accountEdit=(EditText)findViewById(R.id.account); passwordEdit=(EditText)findViewById(R.id.password); checkbox=(CheckBox)findViewById(R.id.remember_password); button=(Button)findViewById(R.id.button); //查看app中是否已經存儲過賬號密碼,有的話就直接顯示出來 boolean isRemember=pref.getBoolean("remember_password",false); if(isRemember){ String account=pref.getString("account",""); String password=pref.getString("password",""); accountEdit.setText(account); passwordEdit.setText(password); checkbox.setChecked(true); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String account=accountEdit.getText().toString(); String password=passwordEdit.getText().toString(); //此處設置的賬號為“admin”,密碼為“123” if(account.equals("admin")&&password.equals("123")){ //如果記住密碼被選中,那麼就將賬號密碼存儲起來 //如果沒有被選中,那麼將存儲的賬號密碼清空 if(checkbox.isChecked()){ editor.putBoolean("remember_password",true); editor.putString("account",account); editor.putString("password",password); }else{ editor.clear(); } //最後千萬不要忘記使用commit將添加的數據提交 editor.commit(); //簡單的跳轉界面 Intent intent=new Intent(MainActivity.this,NextActivity.class); startActivity(intent); finish(); }else{ //如果賬號密碼錯誤,就跳出toast提示,並且清空存儲的賬號密碼 Toast.makeText(MainActivity.this,"賬號或密碼錯誤!",Toast.LENGTH_LONG).show(); editor.clear(); editor.commit(); } } }); } }
activity_main:
<TableLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" 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:stretchColumns="1" tools:context=".MainActivity"> <TableRow> <TextView android:textSize="20sp" android:text="賬號:" android:textColor="#000" android:layout_height="wrap_content"/> <EditText android:id="@+id/account" android:hint="請輸入你的賬號" /> </TableRow> <TableRow> <TextView android:textSize="20sp" android:text="密碼:" android:textColor="#000" android:layout_height="wrap_content"/> <EditText android:id="@+id/password" android:hint="請輸入你的密碼" android:password="true" /> </TableRow> <TableRow> <CheckBox android:id="@+id/remember_password" android:layout_height="wrap_content" android:layout_gravity="center"/> <TextView android:textSize="20sp" android:text="記住密碼" android:layout_height="wrap_content"/> </TableRow> <TableRow> <Button android:id="@+id/button" android:layout_span="2" android:text="確定" android:textSize="25sp"/> </TableRow> </TableLayout>
NextActivity:
import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; public class NextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_next); } }
activity_next:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="登陸成功!" android:textSize="30sp" android:layout_gravity="center_horizontal" /> </LinearLayout>
掌握 SharedPreferences 的讀寫流程後,你就能輕鬆為各種 App 加上「記住設定」這類貼心功能。希望這個範例能幫助你更扎實地理解 Android 的資料持久化。
深入解析 Android 的 MVC 設計模式實戰
轉眼間,我與 Android 開發已相伴走過了兩年時光。這段日子裡,我基本把 Android 的基礎知識摸了个透。可越往深處鑽研,越感到吃力——一方面自以為 Androi
Android 必知必會:動態切換著色模式與全螢幕模式(相容 4.4+)
若行動端閱讀不佳,歡迎改用 ==> Github 版。 本文示範如何透過程式碼動態切換頁面的著色模式與全螢幕模式(沉浸模式),並相容 Android 4.4 以上版
Android 自定義手勢密碼改進版實作
手勢密碼的進化在基礎九宮格手勢密碼上,可以加入更完整的狀態回饋,例如正常、選中與錯誤三種圓點樣式,並在連線時顯示不同線條。這樣的設計能讓使用者更清楚知道目前操作是否正確。
Android Transitions 框架完全解析:一次為多個 View 製作動畫
先前介紹 Animator 時曾提到,那些動畫都是針對單一物件設計的。就算可以對整個 Layout 加效果,本質上仍是「把 Layout 當成一個不可分割的整體」。那如果