Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Fragment 子類與 PreferenceFragment 的創建詳解

編輯:Android 開發實例

Fragment 有靜態與動態兩種使用方式,而 PreferenceFragment 則是快速構建設置頁面的利器。本文將詳細演示 Fragment 子類的兩種創建方式,並深入介紹 PreferenceFragment 的配置與監聽用法。

一、Fragment 的兩種創建方式

1. 靜態方式

第一步,定義一個 Fragment 子類:

public class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

第二步,定義對應的佈局檔 example_fragment.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" >
    <EditText android:id="@+id/edit_message"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint="@string/edit_message" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send"
        android:onClick="sendMessage" />
</LinearLayout>

第三步,在 Activity 的佈局檔中直接引用該 Fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/fragment_intro" />
    <fragment android:name="com.skw.fragmentlayouttest.ExampleFragment"
        android:id="@+id/frag_example"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

2. 動態方式

動態方式的前兩步與靜態相同,差別在於第三步:在 Activity 佈局中定義一個 FrameLayout 作為容器:

<FrameLayout android:id="@+id/frag_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

第四步,在 Activity 中透過 FragmentManager 與 FragmentTransaction 把 Fragment 添加到容器中:

public class FragmentLayoutTest extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        ExampleFragment fragment = new ExampleFragment();
        fragmentTransaction.add(R.id.frag_example, fragment);
        fragmentTransaction.commit();
    }
}

二、PreferenceFragment 使用說明

1. 創建配置文件

新建 res/xml/preferences.xml,定義各項設置:

<PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="PreferenceCategory A">
        <CheckBoxPreference
            android:key="checkbox_preference"
            android:title="title_checkbox_preference"
            android:summary="summary_checkbox_preference" />
    </PreferenceCategory>
    <PreferenceCategory android:title="PreferenceCategory B">
        <EditTextPreference
            android:key="edittext_preference"
            android:title="title_edittext_preference"
            android:summary="null"
            android:dialogTitle="dialog_title_edittext_preference"
            android:defaultValue="null" />
        <ListPreference
            android:key="list_preference"
            android:dialogTitle="Choose font"
            android:entries="@array/pref_font_types"
            android:entryValues="@array/pref_font_types_values"
            android:summary="sans"
            android:title="Font"
            android:defaultValue="sans"/>
    </PreferenceCategory>
    <PreferenceCategory android:title="PreferenceCategory C">
        <SwitchPreference
            android:key="switch_preferece"
            android:title="title_switch_preferece"
            android:defaultValue="true" />
        <SeekBarPreference
            android:key="seekbar_preference"
            android:title="title_seekbar_preference"
            android:max="100"
            android:defaultValue="30" />
    </PreferenceCategory>
</PreferenceScreen>

PreferenceFragment 支持的組件很多,包括 CheckBoxPreference、EditTextPreference、ListPreference、SwitchPreference、SeekBarPreference 等。各屬性含義如下:

(01) android:key 是 Preference 的唯一標識。
(02) android:title 是大標題。
(03) android:summary 是小標題。
(04) android:dialogTitle 是對話框標題。
(05) android:defaultValue 是默認值。
(06) android:entries 是列表各項的說明。
(07) android:entryValues 是列表各項的值。

注意:SwitchPreference 是 API 14(Android 4.0)才支持的,若要用它,需在 manifest 中聲明 <uses-sdk android:minSdkVersion="14" />。

2. 自定義 PreferenceFragment

PreferenceFragment 中的每一項本質上都是一個 SharedPreferences 對象,會存儲在該 APK 的私有數據區。監聽方式常用的有兩種:實現 SharedPreferences.OnSharedPreferenceChangeListener 監聽數據變化,實現 Preference.OnPreferenceClickListener 監聽點擊事件。

public class PrefsFragment extends PreferenceFragment
        implements SharedPreferences.OnSharedPreferenceChangeListener, Preference.OnPreferenceClickListener {
    private static final String CHECK_PREFERENCE = "checkbox_preference";
    private static final String EDITTEXT_PREFERENCE = "edittext_preference";
    private static final String LIST_PREFERENCE = "list_preference";
    private Preference mEditText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        mEditText = (Preference) findPreference(EDITTEXT_PREFERENCE);
        mEditText.setOnPreferenceClickListener(this);
    }
    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals(CHECK_PREFERENCE)) {
            boolean checked = sharedPreferences.getBoolean(key, false);
            // 處理 CheckBox 變化
        } else if (key.equals(EDITTEXT_PREFERENCE)) {
            String value = sharedPreferences.getString(key, "");
            findPreference(key).setSummary(value); // 即時更新小標題
        }
        // 其他類型省略
    }
    @Override
    public void onResume() {
        super.onResume();
        getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }
    @Override
    public void onPause() {
        getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
        super.onPause();
    }
}

別忘了在 onResume 中註冊監聽、在 onPause 中反註冊,避免記憶體洩漏。

3. 使用 PreferenceFragment

定義好 PreferenceFragment 後,只需一行代碼就能把它顯示到 Activity 中:

public class FragmentTest extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new PrefsFragment())
            .commit();
    }
}

透過 PreferenceFragment,你能以極低的成本構建出標準化的設置頁面,各項配置自動持久化,監聽起來也十分方便,是開發設置界面的首選方案。

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