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

Android 設置頁面開發:PreferenceFragment 與自定義 Preference

編輯:關於 Android 程式設計

一個完整的 Android 應用都應該提供設置項,讓用戶能調整 App 的行為表現:是否加入用戶體驗計劃、是否自動升級、定時提醒、開機自啟、後台運行等等。設計得好的設置頁,能顯著提升用戶體驗。

好消息是你不必從零寫 Activity 或 Fragment——Android 已經提供了整套 API,並會自動把用戶的設置以鍵值對形式存入 SharedPreferences。3.0 之前使用 PreferenceActivity,該類在 API level 11(Android 3.0)之後被標記為廢棄,改用 PreferenceFragment。兩者用法大同小異,可根據目標系統版本自行權衡。

一、為 App 添加設置選項

PreferenceFragment 的父類是 Fragment,而 Fragment 必須嵌入 Activity 才能顯示。所以思路很清楚:新建一個 Activity 承載它,剩下的保存與更新交給系統。

1. 編寫 Preference 配置文件

它與 layout 一樣是 XML,但存放在 res/xml 而不是 res/layout。系統提供了不少現成標籤:PreferenceScreen、PreferenceCategory、CheckBoxPreference、SwitchPreference、EditTextPreference、ListPreference 等。

新建 settings.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:preference="https://schemas.android.com/apk/res/com.test.mytest"
    android:title="設置" >

    <PreferenceScreen android:title="關於" >
        <Preference android:title="意見反饋" />

        <com.test.mytest.PreferenceWithTip
            preference:tipstring=">"
            preference:titlestring="自定義測試" >
            <intent
                android:action="android.intent.action.VIEW"
                android:data="https://www.baidu.com" />
        </com.test.mytest.PreferenceWithTip>

        <Preference android:title="常見問題" />
        <Preference android:title="檢查更新" />
        <Preference android:title="版權聲明" />

        <SwitchPreference
            android:key="setting_test"
            android:title="測試一下" />
    </PreferenceScreen>

</PreferenceScreen>

注意 SwitchPreference 的 android:key——它就是寫入 SharedPreferences 時的鍵名,不寫的話系統無法持久化該項的值。

2. 編寫承載 Activity

public class SettingsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        setTitle("選項設置");

        getFragmentManager().beginTransaction()
                .replace(R.id.settings_content, new PrefsFragment())
                .commit();
    }

    public static class PrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings);
        }
    }
}

3. 打開設置頁

不過是啟動一個 Intent 而已。流程到此基本完成。若需要「改動設置後立即反映在界面上」,還要覆寫 onPreferenceTreeClick(PreferenceScreen, Preference) 來攔截具體項目的點擊。

二、自定義 Preference

Preference 直接繼承自 Object,只提供簡單的文本顯示;它的子類 CheckBoxPreference、SwitchPreference、EditTextPreference 則提供更複雜的 UI 並能保存用戶數據。這些子類的用法與在 layout 中用控件幾乎一致,IDE 提示就能搞定。

下面演示如何寫一個帶右側提示文字的 Preference,步驟與自定義控件完全一致。

1)定義屬性 attr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PreferenceWithTip">
        <attr name="tipstring" format="string" />
        <attr name="titlestring" format="string" />
    </declare-styleable>
</resources>

2)設計布局 preferencewithtip.xml

<?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="horizontal"
    android:paddingLeft="8dp"
    android:paddingRight="15dp"
    android:paddingTop="20dp"
    android:paddingBottom="20dp" >

    <TextView
        android:id="@+id/prefs_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:gravity="left|center_vertical"
        android:textSize="18sp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/prefs_tip"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:gravity="right|center_vertical"
        android:textSize="18sp"
        android:layout_weight="1" />

</LinearLayout>

3)繼承 Preference 實現 PreferenceWithTip

public class PreferenceWithTip extends Preference {

    private static final String TAG = "PreferenceWithTip";
    String pTitle = null;
    String tipstring = null;

    public PreferenceWithTip(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // 獲取自定義屬性
        Log.i(TAG, "PreferenceWithTip invoked");
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.PreferenceWithTip);
        tipstring = ta.getString(R.styleable.PreferenceWithTip_tipstring);
        pTitle = ta.getString(R.styleable.PreferenceWithTip_titlestring);
        ta.recycle();       // 記得回收
    }

    public PreferenceWithTip(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        ((TextView) view.findViewById(R.id.prefs_title)).setText(pTitle);
        ((TextView) view.findViewById(R.id.prefs_tip)).setText(tipstring);
    }

    @Override
    protected View onCreateView(ViewGroup parent) {
        return LayoutInflater.from(getContext())
                .inflate(R.layout.preferencewithtip, parent, false);
    }

    // 如需更新、保存數據,繼續補充持久化邏輯
}

4)在 settings.xml 中引用

<com.ict.customview.PreferenceWithTip
    preference:tipstring=">"
    preference:titlestring="自定義測試" >
    <intent
        android:action="android.intent.action.VIEW"
        android:data="https://www.baidu.com" />
</com.ict.customview.PreferenceWithTip>

總結

Preference 的使用相當簡單,自定義也方便——套路和自定義控件幾乎一樣:定義屬性、寫布局、繼承基類、在 XML 中引用。難的反而是設計出一個漂亮且符合用戶直覺的設置頁,這恰恰是提升用戶體驗最值得投入的地方。

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