Android中Fragmen首选项使用自定义的ListPreference的方法

Android中Fragmen首选项使用自定义的ListPreference的方法,第1张

概述首选项这个名词对于熟悉Android的朋友们一定不会感到陌生,它经常用来设置软件的运行参数。

首选项这个名词对于熟悉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 自定义ListPreferenced出的列表选项

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

说明:点击ListPreference,会d出一个列表对话框。通过重写onPrepareDialogBuilder(),我们可以自定义d出的列表对话框。这里是通过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; }}

说明:d出的列表对话框中的每一项的内容是通过布局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>

总结

以上是内存溢出为你收集整理的Android中Fragmen首选项使用自定义的ListPreference的方法全部内容,希望文章能够帮你解决Android中Fragmen首选项使用自定义的ListPreference的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1149261.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存