Android中Fragmen喜好設定使用自訂的ListPreference的方法_Android

來源:互聯網
上載者:User

喜好設定這個名詞對於熟悉Android的朋友們一定不會感到陌生,它經常用來設定軟體的運行參數。
Android提供了一種健壯並且靈活的架構來處理喜好設定。它提供了簡單的API來隱藏喜好設定的讀取和持久化,並且提供了一個優雅的喜好設定介面。
幾種常見的喜好設定:
(1)CheckBoxPreference:用來開啟或關閉某個功能
(2)ListPreference:用來從多個選項中選擇一個值;
(3)EditTextPreference:用來配置一段文字資訊;
(4)Preference:用來執行相關的自訂動作(上圖中的清除緩衝、記錄、表單、cookie都屬於此項);
(5)RingtonePreference:專門用來為使用者佈建鈴聲。
當我們使用喜好設定架構時,使用者每更改一項的值後,系統就會立即在/data/data/[PACKAGE_NAME]/shared_prefs下產生一個[PACKAGE_NAME]_preferences.xml的檔案,檔案會記錄最新的配置資訊。
那麼本文要講的就是其中的ListPreference,以及通過PreferenceFragment來使用自訂的ListPreference。

1. 自訂屬性
添加檔案res/values/attrs.xml,內容如下:

<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="IconListPreference">  <attr name="entryIcons" format="reference" /> </declare-styleable></resources>

說明:
(01) name="IconListPreference",與自訂的ListPreference類的名稱相對應。後面會實現一個繼承於ListPreference的IconListPreference.java。
(02) name="entryIcons",這是屬性的名稱。
(03) format="reference",這描述屬性的值是參考型別。因為,後面會根據資源id設定該屬性,所以將屬性格式設為reference。如果是顏色,設為format="color";如果是布爾類型,format="boolean";如果是字串,設為format="string"。
2. 自訂ListPreference
2.1 建構函式

public IconListPreference(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; // 擷取自訂的屬性(attrs.xml中)對應行的TypedArray TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconListPreference); // 擷取entryIcons屬性對應的值 int iconResId = a.getResourceId(R.styleable.IconListPreference_entryIcons, -1); if (iconResId != -1) {  setEntryIcons(iconResId); }  // 擷取Preferece對應的key mKey = getKey(); // 擷取SharedPreferences mPref = PreferenceManager.getDefaultSharedPreferences(context); // 擷取SharedPreferences.Editor mEditor = mPref.edit(); // 擷取Entry // 注意:如果設定檔中沒有android:entries屬性,則getEntries()為空白; mEntries = getEntries(); // 擷取Entry對應的值 // 注意:如果設定檔中沒有android:entryValues屬性,則getEntries()為空白 mEntryValues = getEntryValues(); // 擷取該ListPreference儲存的值 String value = mPref.getString(mKey, ""); mPosition = findIndexOfValue(value); // 設定Summary if (mPosition!=-1) {  setSummary(mEntries[mPosition]);  setIcon(mEntryIcons[mPosition]); }  a.recycle();}

說明:
(01) 首先,根據obtainStyledAttributes()能擷取自訂屬性對應的TypedArray對象。
(02) 在自訂屬性中,entryIcons對應的類名是IconListPreference。因為需要通過"類名"_"屬性名稱",即IconListPreference_entryIcons的方式來擷取資源資訊。
(03) getKey()是擷取Preferece對應的Key。該Key是Preference對象的唯一標識。
(04) getEntries()是擷取Preferece的Entry數組。
(05) getEntryValues()是擷取Preferece的Entry對應的值的數組。
(06) setSummary()是設定Preferece的summary標題內容。
(07) setIcon()是設定Preferece的表徵圖。
2.2 自訂ListPreference中圖片相關代碼

/** * 設定表徵圖:icons數組 */private void setEntryIcons(int[] entryIcons) { mEntryIcons = entryIcons;}/** * 設定表徵圖:根據icon的id數組 */public void setEntryIcons(int entryIconsResId) { TypedArray icons = getContext().getResources().obtainTypedArray(entryIconsResId); int[] ids = new int[icons.length()]; for (int i = 0; i < icons.length(); i++)  ids[i] = icons.getResourceId(i, -1); setEntryIcons(ids); icons.recycle();}

說明:這兩個函數是讀取圖片資訊的。
2.3 自訂ListPreference彈出的列表選項

@Overrideprotected void onPrepareDialogBuilder(Builder builder) { super.onPrepareDialogBuilder(builder); IconAdapter adapter = new IconAdapter(mContext); builder.setAdapter(adapter, null);}

說明:點擊ListPreference,會彈出一個列表對話方塊。通過重寫onPrepareDialogBuilder(),我們可以自訂彈出的列表對話方塊。這裡是通過IconAdapter來顯示的。

public class IconAdapter extends BaseAdapter{ private LayoutInflater mInflater; public IconAdapter(Context context){  this.mInflater = LayoutInflater.from(context); } @Override public int getCount() {  return mEntryIcons.length; } @Override public Object getItem(int arg0) {  return null; } @Override public long getItemId(int arg0) {  return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) {  ViewHolder holder = null;  if (convertView == null) {   holder = new ViewHolder();   convertView = mInflater.inflate(R.layout.icon_adapter, parent, false);   holder.layout = (LinearLayout)convertView.findViewById(R.id.icon_layout);   holder.img = (ImageView)convertView.findViewById(R.id.icon_img);   holder.info = (TextView)convertView.findViewById(R.id.icon_info);   holder.check = (RadioButton)convertView.findViewById(R.id.icon_check);   convertView.setTag(holder);  }else {   holder = (ViewHolder)convertView.getTag();  }  holder.img.setBackgroundResource(mEntryIcons[position]);  holder.info.setText(mEntries[position]);  holder.check.setChecked(mPosition == position);  final ViewHolder fholder = holder;  final int fpos = position;  convertView.setOnClickListener(new View.OnClickListener() {   @Override   public void onClick(View v) {    v.requestFocus();    // 選中效果    fholder.layout.setBackgroundColor(Color.CYAN);    // 更新mPosition    mPosition = fpos;    // 更新Summary    IconListPreference.this.setSummary(mEntries[fpos]);    IconListPreference.this.setIcon(mEntryIcons[fpos]);    // 更新該ListPreference儲存的值    mEditor.putString(mKey, mEntryValues[fpos].toString());    mEditor.commit();    // 取消ListPreference設定對話方塊    getDialog().dismiss();   }  });  return convertView; } // ListPreference每一項對應的Layout檔案的結構體 private final class ViewHolder {  ImageView img;  TextView info;  RadioButton check;  LinearLayout layout; }}

說明:彈出的列表對話方塊中的每一項的內容是通過布局icon_adapter.xml來顯示的。下面看看icon_adapter.xml的源碼。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/icon_layout"  android:orientation="horizontal" android:paddingLeft="6dp"  android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView  android:id="@+id/icon_img"   android:layout_width="wrap_content"  android:layout_height="wrap_content"   android:gravity="center_vertical"  android:layout_margin="4dp"/> <TextView  android:id="@+id/icon_info"   android:layout_width="0dp"  android:layout_height="wrap_content"   android:layout_weight="1"  android:paddingLeft="6dp"  android:layout_gravity="left|center_vertical"  android:textAppearance="?android:attr/textAppearanceLarge" /> <RadioButton  android:id="@+id/icon_check"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:checked="false"  android:layout_gravity="right|center_vertical"  android:layout_marginRight="6dp"/></LinearLayout>

至此,自訂的ListPreference就算完成了。下面就是如何使用它了。
3. 使用該自訂ListPreference
我們是通過PreferenceFragment使用該自訂的ListPreference。
3.1 PreferenceFragment的設定檔
res/xml/preferences.xml的內容如下:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" xmlns:iconlistpreference="http://schemas.android.com/apk/res/com.skw.fragmenttest"> <!-- 系統預設的ListPreference --> <PreferenceCategory  android:title="PreferenceCategory A">  <!--    (01) android:key是Preferece的id   (02) android:title是Preferece的大標題   (03) android:summary是Preferece的小標題   (04) android:dialogTitle是對話方塊的標題   (05) android:defaultValue是預設值   (06) android:entries是列表中各項的說明   (07) 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> <!-- 自訂的ListPreference --> <PreferenceCategory  android:title="PreferenceCategory B">  <!--    iconlistpreference:entryIcons是自訂的屬性   -->  <com.skw.fragmenttest.IconListPreference   android:key="icon_list_preference"    android:dialogTitle="ChooseIcon"    android:entries="@array/android_versions"   android:entryValues="@array/android_version_values"    iconlistpreference:entryIcons="@array/android_version_icons"   android:icon="@drawable/cupcake"   android:summary="summary_icon_list_preference"   android:title="title_icon_list_preference" />  </PreferenceCategory></PreferenceScreen>

說明:該設定檔中使用了"系統預設的ListPreference"和"自訂的ListPreference(即IconListPreference)"。
注意,IconListPreference中的"iconlistpreference:entryIcons"屬性。前面的"iconlistpreference"與該檔案的命名空間表示"xmlns:iconlistpreference="http://schemas.android.com/apk/res/com.skw.fragmenttest"中的iconlistpreference一樣! 而entryIcons則是我們自訂的屬性名稱。
3.2 自訂PreferenceFragment的代碼

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

4. 使用PrefsFragment
下面,就可以在Activity中使用該PrefsFragment了。
4.1 使用PrefsFragment的Activity的代碼

public class FragmentTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  // 擷取FragmentManager  FragmentManager fragmentManager = getFragmentManager();  // 擷取FragmentTransaction    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  PrefsFragment fragment = new PrefsFragment();  // 將fragment添加到容器frag_example中  fragmentTransaction.add(R.id.prefs, fragment);  fragmentTransaction.commit(); } }

4.2 使用PrefsFragment的Activity的設定檔
res/layout/main.xml的內容如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <FrameLayout  android:id="@+id/prefs"  android:layout_width="match_parent"  android:layout_height="match_parent"/></LinearLayout>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.