Android中Fragmen首選項(xiàng)使用自定義的ListPreference的方法
首選項(xiàng)這個(gè)名詞對(duì)于熟悉Android的朋友們一定不會(huì)感到陌生,它經(jīng)常用來設(shè)置軟件的運(yùn)行參數(shù)。
Android提供了一種健壯并且靈活的框架來處理首選項(xiàng)。它提供了簡(jiǎn)單的API來隱藏首選項(xiàng)的讀取和持久化,并且提供了一個(gè)優(yōu)雅的首選項(xiàng)界面。
幾種常見的首選項(xiàng):
(1)CheckBoxPreference:用來打開或關(guān)閉某個(gè)功能
(2)ListPreference:用來從多個(gè)選項(xiàng)中選擇一個(gè)值;
(3)EditTextPreference:用來配置一段文字信息;
(4)Preference:用來執(zhí)行相關(guān)的自定義操作(上圖中的清除緩存、歷史記錄、表單、cookie都屬于此項(xiàng));
(5)RingtonePreference:專門用來為用戶設(shè)置鈴聲。
當(dāng)我們使用首選項(xiàng)框架時(shí),用戶每更改一項(xiàng)的值后,系統(tǒng)就會(huì)立即在/data/data/[PACKAGE_NAME]/shared_prefs下生成一個(gè)[PACKAGE_NAME]_preferences.xml的文件,文件會(huì)記錄最新的配置信息。
那么本文要講的就是其中的ListPreference,以及通過PreferenceFragment來使用自定義的ListPreference。
1. 自定義屬性
添加文件res/values/attrs.xml,內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="IconListPreference"> <attr name="entryIcons" format="reference" /> </declare-styleable> </resources>
說明:
(01) name="IconListPreference",與自定義的ListPreference類的名稱相對(duì)應(yīng)。后面會(huì)實(shí)現(xiàn)一個(gè)繼承于ListPreference的IconListPreference.java。
(02) name="entryIcons",這是屬性的名稱。
(03) format="reference",這描述屬性的值是引用類型。因?yàn)?,后面?huì)根據(jù)資源id設(shè)置該屬性,所以將屬性格式設(shè)為reference。如果是顏色,設(shè)為format="color";如果是布爾類型,format="boolean";如果是字符串,設(shè)為format="string"。
2. 自定義ListPreference
2.1 構(gòu)造函數(shù)
public IconListPreference(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; // 獲取自定義的屬性(attrs.xml中)對(duì)應(yīng)行的TypedArray TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconListPreference); // 獲取entryIcons屬性對(duì)應(yīng)的值 int iconResId = a.getResourceId(R.styleable.IconListPreference_entryIcons, -1); if (iconResId != -1) { setEntryIcons(iconResId); } // 獲取Preferece對(duì)應(yīng)的key mKey = getKey(); // 獲取SharedPreferences mPref = PreferenceManager.getDefaultSharedPreferences(context); // 獲取SharedPreferences.Editor mEditor = mPref.edit(); // 獲取Entry // 注意:如果配置文件中沒有android:entries屬性,則getEntries()為空; mEntries = getEntries(); // 獲取Entry對(duì)應(yīng)的值 // 注意:如果配置文件中沒有android:entryValues屬性,則getEntries()為空 mEntryValues = getEntryValues(); // 獲取該ListPreference保存的值 String value = mPref.getString(mKey, ""); mPosition = findIndexOfValue(value); // 設(shè)置Summary if (mPosition!=-1) { setSummary(mEntries[mPosition]); setIcon(mEntryIcons[mPosition]); } a.recycle(); }
說明:
(01) 首先,根據(jù)obtainStyledAttributes()能獲取自定義屬性對(duì)應(yīng)的TypedArray對(duì)象。
(02) 在自定義屬性中,entryIcons對(duì)應(yīng)的類名是IconListPreference。因?yàn)樾枰ㄟ^"類名"_"屬性名",即IconListPreference_entryIcons的方式來獲取資源信息。
(03) getKey()是獲取Preferece對(duì)應(yīng)的Key。該Key是Preference對(duì)象的唯一標(biāo)識(shí)。
(04) getEntries()是獲取Preferece的Entry數(shù)組。
(05) getEntryValues()是獲取Preferece的Entry對(duì)應(yīng)的值的數(shù)組。
(06) setSummary()是設(shè)置Preferece的summary標(biāo)題內(nèi)容。
(07) setIcon()是設(shè)置Preferece的圖標(biāo)。
2.2 自定義ListPreference中圖片相關(guān)代碼
/** * 設(shè)置圖標(biāo):icons數(shù)組 */ private void setEntryIcons(int[] entryIcons) { mEntryIcons = entryIcons; } /** * 設(shè)置圖標(biāo):根據(jù)icon的id數(shù)組 */ 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(); }
說明:這兩個(gè)函數(shù)是讀取圖片信息的。
2.3 自定義ListPreference彈出的列表選項(xiàng)
@Override protected void onPrepareDialogBuilder(Builder builder) { super.onPrepareDialogBuilder(builder); IconAdapter adapter = new IconAdapter(mContext); builder.setAdapter(adapter, null); }
說明:點(diǎn)擊ListPreference,會(huì)彈出一個(gè)列表對(duì)話框。通過重寫onPrepareDialogBuilder(),我們可以自定義彈出的列表對(duì)話框。這里是通過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設(shè)置對(duì)話框 getDialog().dismiss(); } }); return convertView; } // ListPreference每一項(xiàng)對(duì)應(yīng)的Layout文件的結(jié)構(gòu)體 private final class ViewHolder { ImageView img; TextView info; RadioButton check; LinearLayout layout; } }
說明:彈出的列表對(duì)話框中的每一項(xiàng)的內(nèi)容是通過布局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的內(nèi)容如下:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" xmlns:iconlistpreference="http://schemas.android.com/apk/res/com.skw.fragmenttest"> <!-- 系統(tǒng)默認(rèn)的ListPreference --> <PreferenceCategory android:title="PreferenceCategory A"> <!-- (01) android:key是Preferece的id (02) android:title是Preferece的大標(biāo)題 (03) android:summary是Preferece的小標(biāo)題 (04) android:dialogTitle是對(duì)話框的標(biāo)題 (05) android:defaultValue是默認(rèn)值 (06) android:entries是列表中各項(xiàng)的說明 (07) android:entryValues是列表中各項(xiàng)的值 --> <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>
說明:該配置文件中使用了"系統(tǒng)默認(rèn)的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中使用該P(yáng)refsFragment了。
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的內(nèi)容如下:
<?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>
- Android中Fragment子類及其PreferenceFragment的創(chuàng)建過程演示
- Android App開發(fā)中創(chuàng)建Fragment組件的教程
- Android中用onSaveInstanceState保存Fragment狀態(tài)的方法
- 實(shí)例探究Android開發(fā)中Fragment狀態(tài)的保存與恢復(fù)方法
- Android中的Fragment類使用進(jìn)階
- Android中使用DialogFragment編寫對(duì)話框的實(shí)例教程
- Android App在ViewPager中使用Fragment的實(shí)例講解
- Android中ViewPager實(shí)現(xiàn)滑動(dòng)指示條及與Fragment的配合
- 淺談Android App開發(fā)中Fragment的創(chuàng)建與生命周期
- Android應(yīng)用開發(fā)中Fragment與Activity間通信示例講解
相關(guān)文章
Android實(shí)現(xiàn)登陸頁logo隨鍵盤收放動(dòng)態(tài)伸縮(完美解決鍵盤彈出遮擋控件的問題)
這篇文章主要介紹了Android實(shí)現(xiàn)登陸頁logo隨鍵盤收放動(dòng)態(tài)伸縮(完美解決鍵盤彈出遮擋控件的問題)的相關(guān)資料,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09Android studio實(shí)現(xiàn)簡(jiǎn)易的計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了Android studio實(shí)現(xiàn)簡(jiǎn)易的計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05View Controller Transition實(shí)現(xiàn)京東加購物車效果
這篇文章主要介紹了View Controller Transition實(shí)現(xiàn)京東加購物車效果,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-02-02Android中快速便捷的實(shí)現(xiàn)圓角按鈕方法詳解
圓角按鈕在我們現(xiàn)在的界面中常常會(huì)用到,最近在開發(fā)中就又遇到了,所以想著有沒有更快速更便捷的實(shí)現(xiàn)方法呢,所以就有了這篇文章,本文主要給大家介紹了關(guān)于Android中如何快速便捷的實(shí)現(xiàn)圓角按鈕的相關(guān)資料,需要的朋友可以參考下。2017-05-05Android?OpenCV基礎(chǔ)API清晰度亮度識(shí)別檢測(cè)
這篇文章主要為大家介紹了Android?OpenCV基礎(chǔ)API清晰度亮度識(shí)別檢測(cè),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01Android 中SwipeRefreshLayout與ViewPager滑動(dòng)事件沖突解決方法
這篇文章主要介紹了Android 中SwipeRefreshLayout與ViewPager滑動(dòng)事件沖突解決方法的相關(guān)資料,需要的朋友可以參考下2017-04-04Android SpannableString設(shè)置超鏈接、顏色、字體等屬性
這篇文章主要介紹了Android SpannableString設(shè)置超鏈接、顏色、字體等屬性的相關(guān)資料,需要的朋友可以參考下2017-01-01