国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android中Fragmen首選項使用自定義的ListPreference的方法

2019-12-12 06:24:54
字體:
供稿:網(wǎng)友

首選項這個名詞對于熟悉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彈出的列表選項

@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設(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中使用該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的內(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>

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 长武县| 武宣县| 宁波市| 新乡县| 东安县| 泸水县| 河北省| 海林市| 金溪县| 隆林| 环江| 正蓝旗| 大庆市| 手机| 北辰区| 卢湾区| 喀什市| 博罗县| 淮安市| 南开区| 安乡县| 五指山市| 汝南县| 库尔勒市| 衡阳市| 顺平县| 深圳市| 江川县| 洛隆县| 九龙坡区| 顺义区| 子洲县| 外汇| 惠水县| 西林县| 绥中县| 修文县| 英超| 昌平区| 克什克腾旗| 昌平区|