Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

登入時記住使用者名稱:SharedPreferences 實作教學

編輯:關於 Android 開發

看完課程影片後自己動手做的筆記。課程影片:https://www.imooc.com/video/3265

功能目標

這個小範例示範如何用 SharedPreferences 記住上次登入成功的使用者名稱,共三種情境:

  • 輸入錯誤的使用者名稱與密碼,按下登入 → 彈出提示「禁止登錄」。
  • 輸入正確的帳密,按下登入 → 彈出提示「登錄成功」。
  • 輸入正確帳密並勾選「保存用戶名」後登入,結束 App 再重新開啟 → 使用者名稱欄位已自動帶入。

版面配置

activity_main.xml:

<RelativeLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:text="用戶名:" />

    <EditText
        android:id="@+id/etuserName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView1"
        android:layout_toRightOf="@+id/textView1"
        android:ems="10" />

    <TextView
        android:id="@+id/aa"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/etuserName"
        android:text="密 碼" />

    <EditText
        android:id="@+id/etuserPass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/etuserName"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/aa"
        android:ems="10">
        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/etuserPass"
        android:layout_marginTop="62dp"
        android:onClick="doClick"
        android:text="登陸" />

    <Button
        android:id="@+id/btnCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btnLogin"
        android:layout_alignBottom="@+id/btnLogin"
        android:layout_toRightOf="@+id/btnLogin"
        android:onClick="doClick"
        android:text="取消" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/btnCancel"
        android:layout_below="@+id/etuserPass"
        android:layout_marginTop="15dp"
        android:checked="false"
        android:text="保存用戶名" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    EditText etUserName, etUserPass;
    CheckBox chk;
    SharedPreferences pref;
    Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 綁定版面控制項
        etUserName = (EditText) findViewById(R.id.etuserName);
        etUserPass = (EditText) findViewById(R.id.etuserPass);
        chk = (CheckBox) findViewById(R.id.checkBox1);

        pref = getSharedPreferences("UserInfo", MODE_PRIVATE);
        editor = pref.edit();

        // 啟動時先試著讀回上次記住的使用者名稱
        String name = pref.getString("userName", "");
        if (name == null) {
            chk.setChecked(false);
        } else {
            chk.setChecked(true);
            etUserName.setText(name);
        }
    }

    // 兩個按鈕共用的回呼
    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:
                String name = etUserName.getText().toString().trim();
                String pass = etUserPass.getText().toString().trim();

                if ("admin".equals(name) && "123456".equals(pass)) {
                    if (chk.isChecked()) {
                        // 帳密正確且勾選了記住名稱 → 寫入偏好檔
                        editor.putString("userName", name);
                        editor.commit();
                    } else {
                        // 沒勾選 → 清掉舊紀錄,避免下次仍被帶入
                        editor.remove("userName");
                        editor.commit();
                    }
                    Toast.makeText(MainActivity.this, "登錄成功", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "禁止登錄", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }
}

整段邏輯的核心其實只有三件事:onCreate() 讀回偏好檔並回填欄位、登入成功時依勾選狀態決定 putString() 或 remove()、以及每次修改後都要 commit()。這裡把帳密寫死在程式碼中只是為了示範,正式專案請勿沿用,應改由伺服器端驗證並以更安全的方式保存憑證。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved