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

Android 開發實戰(十一):PreferenceActivity 與四種設定元件完整用法

編輯:關於 Android 開發

為什麼需要 PreferenceActivity

PreferenceActivity 繼承自 ListActivity,以清單形式呈現設定項目。它最大的特色是:你只要把 Preference 放上去,控制項的狀態就會自動持久化,不必自己寫一行讀寫 SharedPreferences 的程式。

舉個最常見的場景:使用者勾選了一個 CheckBox,退出應用,再打開時他期待那個勾還在。若全靠手寫,你得在每次操作後存檔、每次進入 Activity 時讀檔、再逐一還原每個控制項的狀態——設定項目一多,這段程式會迅速膨脹成一團。Preference 機制正是為了解掉這件事:使用者操作時,它以鍵值對形式即時寫入 SharedPreferences;Activity 啟動時,它自動把值讀回來並套進 UI。

Android 一共提供四種內建元件:CheckBoxPreference、EditTextPreference、ListPreference、RingtonePreference。以下逐一示範。

CheckBoxPreference

勾選為 true,取消為 false,以 boolean 存入 SharedPreferences。

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="CheckBoxPreference">
        <CheckBoxPreference android:key="checkbox_0"
            android:title="CheckBox_A"
            android:summary="這是一個勾選框 A" />
        <CheckBoxPreference android:key="checkbox_1"
            android:title="CheckBox_B"
            android:summary="這是一個勾選框 B" />
    </PreferenceCategory>
</PreferenceScreen>

程式碼端透過 findPreference(key) 取得物件,掛上兩種監聽器:

CheckBoxPreference mCheckbox0 = (CheckBoxPreference) findPreference("checkbox_0");

mCheckbox0.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        // 監聽「被點擊」這件事
        return true;
    }
});

mCheckbox0.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference arg0, Object newValue) {
        // 監聽「值改變」,並能拿到新值
        Toast.makeText(mContext, "checkBox_0 改變的值為" + (Boolean) newValue, Toast.LENGTH_LONG).show();
        return true;
    }
});

兩者的差別值得記住:OnPreferenceClickListener 管的是「按下去」這個動作,OnPreferenceChangeListener 管的是「值真的變了」,而且回呼裡的 newValue 就是新值。另外別忘了回傳 true——回傳 false 代表你否決這次變更。

還有一個關鍵是 android:key:它就是這項設定在 SharedPreferences 中的名稱;而 addPreferencesFromResource() 則是讓系統自動完成存取的那把鑰匙。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 從資源檔載入設定,選擇的值會自動存進 SharedPreferences
    addPreferencesFromResource(R.xml.checkbox);
    mContext = this;
    // 後續以 findPreference 取得各元件
}

EditTextPreference

點擊後彈出輸入框,輸入內容以字串形式保存。

<EditTextPreference android:key="edit_0"
    android:title="輸入資訊_A"
    android:summary="請輸入您的資訊"
    android:defaultValue="請輸入資訊"
    android:dialogTitle="輸入框" />

對話框的按鈕文字與圖示都能客製:

EditTextPreference mEditText = (EditTextPreference) findPreference("edit_0");
mEditText.setPositiveButtonText("確定");
mEditText.setNegativeButtonText("取消");
mEditText.setDialogIcon(R.drawable.jay);

ListPreference

先在 res/values 下準備兩個陣列,一個給清單顯示用,一個給實際存取值用:

<string-array name="auto_logout_time_key">
    <item>10 mins.</item>
    <item>20 mins.</item>
    <item>30 mins.</item>
    <item>60 mins.</item>
</string-array>

<string-array name="auto_logout_time_value">
    <item>600000</item>
    <item>1200000</item>
    <item>1800000</item>
    <item>3600000</item>
</string-array>

點擊後彈出清單,選中項會把「value 陣列裡對應的那個值」以字串存進 SharedPreferences。

<ListPreference
    android:key="list_0"
    android:title="登錄設定"
    android:dialogTitle="選擇在線時間"
    android:entries="@array/auto_logout_time_key"
    android:entryValues="@array/auto_logout_time_value" />

entries 是使用者看到的文字,entryValues 是存進去的值,兩者靠索引一一對應,順序不能錯開。程式碼極簡:

public class ListActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.list);
    }
}

RingtonePreference

點擊後叫出系統鈴聲清單,選好之後存的是一個 URI 字串。

<RingtonePreference
    android:key="ringtone_0"
    android:title="鈴聲設定"
    android:summary="選擇系統鈴聲"
    android:ringtoneType="all"
    android:showSilent="true" />

android:ringtoneType 有四種:鈴聲(ringtone)、通知(notification)、鬧鐘(alarm)、全部(all)。

模擬器預設沒有鈴聲可選,把音樂檔丟進 SD 卡、到系統設定裡指定為鈴聲之後,清單裡才會出現。

自定義 Preference

系統預設樣式比較樸素,要做好看的設定頁就得自訂版面。第一步是在 res/layout 裡寫一個自己的配置檔:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00000000">

    <LinearLayout
        android:gravity="center_vertical"
        android:background="@drawable/preference_mid_background"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:focusable="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/setting_about_us" />

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dip"
            android:layout_marginTop="6dip"
            android:layout_marginRight="6dip"
            android:layout_marginBottom="6dip"
            android:layout_weight="1">

            <TextView
                android:id="@android:id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="15dip"
                android:textColor="#000000"
                android:ellipsize="marquee"
                android:singleLine="true" />

            <TextView
                android:id="@android:id/summary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="#565656"
                android:maxLines="4"
                android:layout_below="@android:id/title"
                android:layout_alignLeft="@android:id/title" />
        </RelativeLayout>

        <ImageView
            android:focusable="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/preference_arrows" />
    </LinearLayout>
</LinearLayout>

這裡有個不能改的細節:標題與摘要的 id 必須寫成 @android:id/title 和 @android:id/summary,因為 Preference 框架就是靠這兩個 id 去填內容的。

再來是背景:android:background="@drawable/preference_mid_background" 指向一個 selector,用來定義按下、獲得焦點、預設三種狀態的外觀。

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_focused="true"
        android:drawable="@drawable/preference_mid_pressed" />
    <item android:state_pressed="true"
        android:drawable="@drawable/preference_mid_pressed" />
    <item android:drawable="@drawable/preference_mid" />
</selector>

規則是:具名的狀態寫在前面,最後那個不帶條件的項目就是預設樣貌。

最後在 PreferenceScreen 中透過 android:layout 指向自訂版面,再用 findPreference 掛監聽即可:

preference0 = findPreference("pref_key_0");
preference0.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        Toast.makeText(mContext, "自定義佈局 A 被按下", Toast.LENGTH_LONG).show();
        return false;
    }
});

怎麼把值讀出來

需要主動取值的時候,透過 PreferenceManager 拿到預設的 SharedPreferences:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean something = prefs.getBoolean("something", false);

把模擬器裡的 SharedPreferences 檔案拉出來,會看到點選後實際存下的內容:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="ringtone_0">content://media/external/audio/media/1</string>
    <string name="list_0">1800000</string>
    <string name="edit_0">請輸入資訊</string>
    <boolean name="checkbox_0" value="true" />
    <boolean name="checkbox_1" value="true" />
</map>

鈴聲存的是一個 URI 字串,指向系統媒體庫裡的實際路徑,拿著它就能定位到那個音檔。看到這份 XML,你也就明白 Preference 到底替你做了哪些事。

源碼下載地址:https://vdisk.weibo.com/s/aa3UT

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