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

Fragment 的靜態與動態建立方式,以及 PreferenceFragment 設定頁實作

編輯:關於 Android 程式設計

Fragment 有兩種典型的使用方式:靜態方式(寫在版面 XML 裡)與動態方式(在程式碼中用 FragmentTransaction 掛載)。本文先後示範這兩條路徑,再進一步說明如何用 PreferenceFragment 做出一個功能完整的設定頁面。

一、靜態方式

步驟 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);
     }
 }

步驟 2:撰寫對應版面 example_fragment.xml

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 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: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>

步驟 3:在 Activity 的版面中引用它

 public class FragmentLayoutTest extends Activity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
 }
 <?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>

透過 <fragment> 標籤的 android:name,Fragment 會在 Activity 版面 inflate 時一併建立。這種寫法簡單,但缺點是執行期無法移除或替換。

二、動態方式

Fragment 子類與版面沿用上面的內容,差別在第三步之後。

步驟 3:版面中放一個空的 FrameLayout 當容器

 <?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" />

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

步驟 4:在程式碼中把 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();
     }
 }

動態方式的好處是可以在執行期任意 add、replace、remove,並搭配 addToBackStack() 支援返回鍵。

三、PreferenceFragment 使用說明

1. 建立設定檔 res/xml/preferences.xml

 <PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android">

     <PreferenceCategory android:title="PreferenceCategory A">
         <!--
             (01) android:key 是 Preference 的 id,也是唯一識別
             (02) android:title 是主標題
             (03) android:summary 是副標題
         -->
         <CheckBoxPreference
             android:key="checkbox_preference"
             android:title="title_checkbox_preference"
             android:summary="summary_checkbox_preference" />
     </PreferenceCategory>

     <PreferenceCategory android:title="PreferenceCategory B">
         <!-- android:dialogTitle 是對話框標題;android:defaultValue 是預設值 -->
         <EditTextPreference
             android:key="edittext_preference"
             android:title="title_edittext_preference"
             android:summary="null"
             android:dialogTitle="dialog_title_edittext_preference"
             android:defaultValue="null" />

         <!-- android:entries 是選項說明;android:entryValues 是選項值 -->
         <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 可用的元件相當豐富,除了上面用到的,還有 VolumePreference 等。共同屬性整理如下:

  • android:key:Preference 的 id,唯一識別。
  • android:title:主標題。
  • android:summary:副標題。
  • android:dialogTitle:彈出對話框的標題。
  • android:defaultValue:預設值。
  • android:entries:清單中各選項的說明文字。
  • android:entryValues:清單中各選項對應的值。

版本注意:SwitchPreference 是 API 14(Android 4.0)才支援的,若要使用,必須在 manifest 中宣告最低支援版本:

 <uses-sdk android:minSdkVersion="14" />

2. 自訂 PreferenceFragment

 public class PrefsFragment extends PreferenceFragment
         implements SharedPreferences.OnSharedPreferenceChangeListener,
                    Preference.OnPreferenceClickListener {

     private static final String TAG = "##PrefsFragment##";
     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 static final String SWITCH_PREFERENCE = "switch_preferece";
     private static final String SEEKBAR_PREFERENCE = "seekbar_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) {
         Preference connectionPref = findPreference(key);
         if (key.equals(CHECK_PREFERENCE)) {
             boolean checked = sharedPreferences.getBoolean(key, false);
             Log.d(TAG, "CheckBox: checked=" + checked);
         } else if (key.equals(EDITTEXT_PREFERENCE)) {
             String value = sharedPreferences.getString(key, "");
             connectionPref.setSummary(value);
             Log.d(TAG, "EditText: value=" + value);
         } else if (key.equals(LIST_PREFERENCE)) {
             String value = sharedPreferences.getString(key, "");
             connectionPref.setSummary(value);
             Log.d(TAG, "List: value=" + value);
         } else if (key.equals(SWITCH_PREFERENCE)) {
             boolean checked = sharedPreferences.getBoolean(key, false);
             Log.d(TAG, "Switch: checked=" + checked);
         } else if (key.equals(SEEKBAR_PREFERENCE)) {
             int value = sharedPreferences.getInt(key, 0);
             Log.d(TAG, "Seekbar: value=" + value);
         }
     }

     @Override
     public boolean onPreferenceClick(Preference preference) {
         SharedPreferences sharedPreferences = preference.getSharedPreferences();
         String value = sharedPreferences.getString(preference.getKey(), "");
         Log.d(TAG, "onPreferenceClick: value=" + value);
         return true;
     }

     @Override
     public void onResume() {
         super.onResume();
         getPreferenceManager().getSharedPreferences()
                 .registerOnSharedPreferenceChangeListener(this);
     }

     @Override
     public void onPause() {
         getPreferenceManager().getSharedPreferences()
                 .unregisterOnSharedPreferenceChangeListener(this);
         super.onPause();
     }
 }

要理解這段程式碼,先記住一個觀念:PreferenceFragment 中的每一項設定,本質上都是一個 SharedPreferences 項目,會存在該 APK 的私有資料區。監聽變化的方式主要有兩種:

  • 監聽資料變化:實作 SharedPreferences.OnSharedPreferenceChangeListener,在 onSharedPreferenceChanged() 中依 key 分別處理。別忘了在 onResume() 註冊、onPause() 取消註冊,否則容易造成記憶體洩漏。
  • 監聽點擊事件:實作 Preference.OnPreferenceClickListener,用來攔截特定項目的點擊行為(例如做一個「清除快取」的入口)。

3. 在 Activity 中呈現

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

這裡直接把 Fragment 掛到 android.R.id.content,也就是整個視窗的內容區,因此不必另外準備版面檔——這是快速做出一個獨立設定頁的簡便寫法。

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