Android中Fragmen首選項使用自定義的ListPreference的方法
首選項這個名詞對于熟悉Android的朋友們一定不會感到陌生,它經(jīng)常用來設(shè)置軟件的運行參數(shù)。
Android提供了一種健壯并且靈活的框架來處理首選項。它提供了簡單的API來隱藏首選項的讀取和持久化,并且提供了一個優(yōu)雅的首選項界面。
幾種常見的首選項:
(1)CheckBoxPreference:用來打開或關(guān)閉某個功能
(2)ListPreference:用來從多個選項中選擇一個值;
(3)EditTextPreference:用來配置一段文字信息;
(4)Preference:用來執(zhí)行相關(guān)的自定義操作(上圖中的清除緩存、歷史記錄、表單、cookie都屬于此項);
(5)RingtonePreference:專門用來為用戶設(shè)置鈴聲。
當(dāng)我們使用首選項框架時,用戶每更改一項的值后,系統(tǒng)就會立即在/data/data/[PACKAGE_NAME]/shared_prefs下生成一個[PACKAGE_NAME]_preferences.xml的文件,文件會記錄最新的配置信息。
那么本文要講的就是其中的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類的名稱相對應(yīng)。后面會實現(xiàn)一個繼承于ListPreference的IconListPreference.java。
(02) name="entryIcons",這是屬性的名稱。
(03) format="reference",這描述屬性的值是引用類型。因為,后面會根據(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中)對應(yīng)行的TypedArray
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconListPreference);
// 獲取entryIcons屬性對應(yīng)的值
int iconResId = a.getResourceId(R.styleable.IconListPreference_entryIcons, -1);
if (iconResId != -1) {
setEntryIcons(iconResId);
}
// 獲取Preferece對應(yīng)的key
mKey = getKey();
// 獲取SharedPreferences
mPref = PreferenceManager.getDefaultSharedPreferences(context);
// 獲取SharedPreferences.Editor
mEditor = mPref.edit();
// 獲取Entry
// 注意:如果配置文件中沒有android:entries屬性,則getEntries()為空;
mEntries = getEntries();
// 獲取Entry對應(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()能獲取自定義屬性對應(yīng)的TypedArray對象。
(02) 在自定義屬性中,entryIcons對應(yīng)的類名是IconListPreference。因為需要通過"類名"_"屬性名",即IconListPreference_entryIcons的方式來獲取資源信息。
(03) getKey()是獲取Preferece對應(yīng)的Key。該Key是Preference對象的唯一標(biāo)識。
(04) getEntries()是獲取Preferece的Entry數(shù)組。
(05) getEntryValues()是獲取Preferece的Entry對應(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();
}
說明:這兩個函數(shù)是讀取圖片信息的。
2.3 自定義ListPreference彈出的列表選項
@Override
protected 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設(shè)置對話框
getDialog().dismiss();
}
});
return convertView;
}
// ListPreference每一項對應(yīng)的Layout文件的結(jié)構(gòu)體
private final class ViewHolder {
ImageView img;
TextView info;
RadioButton check;
LinearLayout layout;
}
}
說明:彈出的列表對話框中的每一項的內(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是對話框的標(biāo)題 (05) android:defaultValue是默認(rèn)值 (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>
說明:該配置文件中使用了"系統(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)的方法
- 實例探究Android開發(fā)中Fragment狀態(tài)的保存與恢復(fù)方法
- Android中的Fragment類使用進(jìn)階
- Android中使用DialogFragment編寫對話框的實例教程
- Android App在ViewPager中使用Fragment的實例講解
- Android中ViewPager實現(xiàn)滑動指示條及與Fragment的配合
- 淺談Android App開發(fā)中Fragment的創(chuàng)建與生命周期
- Android應(yīng)用開發(fā)中Fragment與Activity間通信示例講解
相關(guān)文章
Android檢查手機(jī)有沒有安裝某應(yīng)用的方法
這篇文章主要介紹了Android檢查手機(jī)有沒有安裝某應(yīng)用的方法,分析總結(jié)了幾種常用的判斷技巧,涉及Android針對應(yīng)用程序包的相關(guān)讀取與判定技巧,需要的朋友可以參考下2016-08-08
android同時控制EditText輸入字符個數(shù)和禁止特殊字符輸入的方法
這篇文章主要介紹了android同時控制EditText輸入字符個數(shù)和禁止特殊字符輸入的方法,涉及Android操作EditText控制字符操作的技巧,需要的朋友可以參考下2015-04-04
Android?Kotlin全面詳細(xì)類使用語法學(xué)習(xí)指南
這篇文章主要為大家介紹了Android?Kotlin全面詳細(xì)類使用語法學(xué)習(xí)指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Android實現(xiàn)QQ手機(jī)管家懸浮小火箭效果
這篇文章主要介紹了Android實現(xiàn)QQ手機(jī)管家懸浮小火箭效果,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Android OpenGL ES實現(xiàn)簡單綠幕摳圖
這篇文章主要為大家介紹了Android OpenGL ES實現(xiàn)簡單綠幕摳圖示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Android編程動態(tài)加載布局實例詳解【附demo源碼】
這篇文章主要介紹了Android編程動態(tài)加載布局,結(jié)合實例形式分析了Android動態(tài)加載布局的原理、操作步驟與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2016-10-10
Android實現(xiàn)把文件存放在SDCard的方法
這篇文章主要介紹了Android實現(xiàn)把文件存放在SDCard的方法,涉及Android針對SDCard的讀寫技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09

