SoFunction
Updated on 2025-04-06

Method of using custom ListPreference for Fragmen preferences in Android

The term preference will definitely not be unfamiliar to friends who are familiar with Android. It is often used to set the operating parameters of the software.
Android provides a robust and flexible framework to handle preferences. It provides a simple API to hide the read and persistence of preferences, and provides an elegant preference interface.
Several common preferences:
(1) CheckBoxPreference: used to turn on or off a function
(2) ListPreference: used to select a value from multiple options;
(3) EditTextPreference: used to configure a piece of text information;
(4) Preference: used to perform related custom operations (clear cache, history, forms, and cookies in the above figure all belong to this item);
(5) RingtonePreference: specially used to set ringtones for users.
When we use the preference framework, every time the user changes the value of an item, the system will immediately generate a [PACKAGE_NAME]_preferences.xml file under /data/data/[PACKAGE_NAME]/shared_prefs, and the file will record the latest configuration information.
So what this article will talk about is ListPreference and the use of customized ListPreference through PreferenceFragment.

1. Custom properties
Add the file res/values/, the content is as follows:

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

illustrate:
(01) name="IconListPreference", corresponding to the name of the customized ListPreference class. Later, a ListPreference inherited will be implemented.
(02) name="entryIcons", which is the name of the property.
(03) format="reference", which describes the value of the attribute as a reference type. Because this attribute will be set according to the resource id later, the attribute format is set to reference. If it is a color, set to format="color"; if it is a boolean, format="boolean"; if it is a string, set to format="string".
2. Customize ListPreference
2.1 Constructor

public IconListPreference(Context context, AttributeSet attrs) {
 super(context, attrs);
 mContext = context;

 // Get the TypedArray of the corresponding row of the custom attribute (in) TypedArray a = (attrs, );
 // Get the value corresponding to the entryIcons attribute int iconResId = (.IconListPreference_entryIcons, -1);
 if (iconResId != -1) {
  setEntryIcons(iconResId);
 } 

 // Get the corresponding key of Preference mKey = getKey();
 // Get SharedPreferences mPref = (context);
 // Get mEditor = ();
 // Get Entry // Note: if there is no android:entries attribute in the configuration file, getEntries() is empty; mEntries = getEntries();
 // Get the value corresponding to Entry // Note: if there is no android:entryValues ​​property in the configuration file, getEntries() is empty mEntryValues = getEntryValues();

 // Get the value saved by this ListPreference String value = (mKey, "");
 mPosition = findIndexOfValue(value);
 // Set Summary if (mPosition!=-1) {
  setSummary(mEntries[mPosition]);
  setIcon(mEntryIcons[mPosition]);
 } 

 ();
}

illustrate:
(01) First, according to obtainStyledAttributes(), you can obtain the TypedArray object corresponding to the custom attribute.
(02) In the custom attribute, the class name corresponding to entryIcons is IconListPreference. Because you need to obtain resource information through the "class name"_"attribute name", that is, IconListPreference_entryIcons method.
(03) getKey() is to get the key corresponding to Preference. The Key is the unique identifier of the Preference object.
(04) getEntries() is the Entry array that gets Preference.
(05) getEntryValues() is an array that gets the value corresponding to the Entry of Preference.
(06) setSummary() is the summary title content that sets Preference.
(07) setIcon() is the icon that sets Preference.
2.2 Customize the picture-related code in ListPreference

/**
  * Settings icon: icons array
  */
private void setEntryIcons(int[] entryIcons) {
 mEntryIcons = entryIcons;
}

/**
  * Set icon: array of ids according to icon
  */
public void setEntryIcons(int entryIconsResId) {
 TypedArray icons = getContext().getResources().obtainTypedArray(entryIconsResId);
 int[] ids = new int[()];
 for (int i = 0; i &lt; (); i++)
  ids[i] = (i, -1);
 setEntryIcons(ids);
 ();
}

Note: These two functions read image information.
2.3 Customize the list options pop-up by ListPreference

@Override
protected void onPrepareDialogBuilder(Builder builder) {
 (builder);

 IconAdapter adapter = new IconAdapter(mContext);
 (adapter, null);
}

Description: Click ListPreference and a list dialog box will pop up. By rewriting onPrepareDialogBuilder(), we can customize the pop-up list dialog box. This is displayed via IconAdapter.

public class IconAdapter extends BaseAdapter{

 private LayoutInflater mInflater;


 public IconAdapter(Context context){
   = (context);
 }
 @Override
 public int getCount() {
  return ;
 }

 @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 = (.icon_adapter, parent, false);
    = (LinearLayout)(.icon_layout);
    = (ImageView)(.icon_img);
    = (TextView)(.icon_info);
    = (RadioButton)(.icon_check);
   (holder);

  }else {
   holder = (ViewHolder)();
  }

  (mEntryIcons[position]);
  (mEntries[position]);
  (mPosition == position);

  final ViewHolder fholder = holder;
  final int fpos = position;
  (new () {

   @Override
   public void onClick(View v) {
    ();
    // Select the effect    ();

    // Update mPosition    mPosition = fpos;
    // Update Summary    (mEntries[fpos]);
    (mEntryIcons[fpos]);
    // Update the value saved by this ListPreference    (mKey, mEntryValues[fpos].toString());
    ();

    // Cancel ListPreference Settings dialog box    getDialog().dismiss();
   }
  });

  return convertView;
 }

 // ListPreference for each item of the Layout file structure private final class ViewHolder {
  ImageView img;
  TextView info;
  RadioButton check;
  LinearLayout layout;
 }
}

Description: The contents of each item in the pop-up list dialog box are displayed by layout icon_adapter.xml. Let’s take a look at the source code of icon_adapter.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
 android: 
 android:orientation="horizontal"
 android:paddingLeft="6dp" 
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">


 <ImageView
  android: 
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" 
  android:gravity="center_vertical"
  android:layout_margin="4dp"/>

 <TextView
  android: 
  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:
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:checked="false"
  android:layout_gravity="right|center_vertical"
  android:layout_marginRight="6dp"/>

</LinearLayout>

At this point, the customized ListPreference is completed. Here is how to use it.
3. Use this custom ListPreference
We are using this custom ListPreference through PreferenceFragment.
3.1 PreferenceFragment configuration file
The content of res/xml/ is as follows:

&lt;PreferenceScreen xmlns:andro
 xmlns:iconlistpreference="/apk/res/"&gt;

 &lt;!-- System defaultListPreference --&gt;
 &lt;PreferenceCategory
  android:title="PreferenceCategory A"&gt;

  &lt;!-- 
   (01) android:keyyesPrefereceofid
   (02) android:titleyesPrefereceof大标题
   (03) android:summaryyesPrefereceof小标题
   (04) android:dialogTitleyes对话框of标题
   (05) android:defaultValueyes默认值
   (06) android:entriesyes列表中各项of说明
   (07) android:entryValuesyes列表中各项of值
   --&gt;
  &lt;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"/&gt; 
 &lt;/PreferenceCategory&gt;

 &lt;!-- 自定义ofListPreference --&gt;

 &lt;PreferenceCategory
  android:title="PreferenceCategory B"&gt;

  &lt;!-- 
   iconlistpreference:entryIconsyes自定义of属性
   --&gt;
  &lt;
   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" /&gt; 

 &lt;/PreferenceCategory&gt;

&lt;/PreferenceScreen&gt;

Note: "System default ListPreference" and "custom ListPreference (i.e. IconListPreference)" are used in this configuration file.
Note that the "iconlistpreference:entryIcons" property in the IconListPreference. The previous "iconlistpreference" is the same as the iconlistpreference in the namespace of the file "xmlns:iconlistpreference="/apk/res/"! entryIcons is our custom attribute name.
3.2 Code for customizing PreferenceFragment

public class PrefsFragment extends PreferenceFragment {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);

  addPreferencesFromResource();
 }

 ...
}

4. Use PrefsFragment
Next, you can use the PrefsFragment in the Activity.
4.1 Code for Activity using PrefsFragment

public class FragmentTest extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView();

  // Get FragmentManager  FragmentManager fragmentManager = getFragmentManager();
  // Get FragmentTransaction  FragmentTransaction fragmentTransaction = ();

  PrefsFragment fragment = new PrefsFragment();
  // Add fragment to container fragment_example  (, fragment);
  ();
 } 
}

4.2 Configuration file for Activity using PrefsFragment
The content of res/layout/ is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >

 <FrameLayout
  android:
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

</LinearLayout>