Android fragmen Preferences Use a custom Listpreference method _android

Source: Internet
Author: User
Tags commit

Preferences this term is not unfamiliar to friends who are familiar with Android, and it is often used to set the running parameters of the software.
Android provides a robust and flexible framework for handling preferences. It provides a simple API to hide the reading and persistence of preferences, and provides an elegant preference interface.
Several common preferences:
(1) Checkboxpreference: Used to turn a feature on or off
(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 actions (the purge cache, history, form, cookie in the image above);
(5) Ringtonepreference: specifically used to set ringtones for users.
When we use the preference framework, every time a user changes the value of one item, the system immediately generates a [Package_name]_/data/data/[package_name]/shared_prefs Preferences.xml file, the file records the latest configuration information.
So this article is about the listpreference, and through preferencefragment to use the custom listpreference.

1. Custom Properties
Add File Res/values/attrs.xml, which reads as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
 <declare-styleable name= " Iconlistpreference ">
  <attr name=" entryicons "format=" reference "/>
 </declare-styleable>
</resources>

Description:
name= "Iconlistpreference" and corresponds to the name of a custom listpreference class. A iconlistpreference.java that inherits from Listpreference will be implemented later.
() name= "Entryicons", which is the name of the property.
(s) format= "Reference", which describes the value of the property as a reference type. Because this property is set later based on the resource ID, the property format is set to reference. If it is a color, set to format= "color", if it is a Boolean type, format= "Boolean", and if it is a string, set to Format= "string".
2. Custom Listpreference
2.1 constructors

Public iconlistpreference (context, AttributeSet attrs) {Super (context, attrs);

 Mcontext = context; Gets the TypedArray TypedArray a = Context.obtainstyledattributes of the corresponding row in the custom attribute (Attrs.xml) (Attrs,
 R.styleable.iconlistpreference);
 Gets the value of the Entryicons property int iconresid = A.getresourceid (r.styleable.iconlistpreference_entryicons,-1);
 if (Iconresid!=-1) {setentryicons (ICONRESID);
 //Get preferece corresponding key Mkey = Getkey ();
 Get sharedpreferences Mpref = preferencemanager.getdefaultsharedpreferences (context);
 Get Sharedpreferences.editor Meditor = Mpref.edit ();
 Get entry//NOTE: If there is no android:entries attribute in the configuration file, then GetEntries () is empty; mentries = GetEntries ();

 Get entry corresponding Value//NOTE: If there is no android:entryvalues attribute in the configuration file, then GetEntries () is empty mentryvalues = Getentryvalues ();
 Gets the value stored by the listpreference String value = mpref.getstring (Mkey, "");
 Mposition = Findindexofvalue (value);
  Set Summary if (mposition!=-1) {setsummary (mentries[mposition]);
 SetIcon (Mentryicons[mposition]); } A.REcycle ();

 }

Description
(01) First, the Typedarray object corresponding to the custom attribute can be obtained according to Obtainstyledattributes ().
(02) In the custom attribute, the entryicons corresponding class name is iconlistpreference. Because you need to use the class name _ "property name", that is, the iconlistpreference_entryicons of the way to obtain resource information.
Getkey () is the key that gets the preferece corresponding. The key is the unique identifier of the preference object.
GetEntries () is a entry array that gets preferece.
() Getentryvalues () is an array of values that obtain the entry corresponding to the preferece.
Setsummary () is the summary header content that sets the preferece.
SetIcon () is the icon to set the preferece.
2.2 Custom Listpreference picture-related code

/**
 * Setting icon: Icons array
/private void Setentryicons (int[] entryicons) {
 mentryicons = entryicons;
}

/**
 * Setting icon: According to Icon's ID
 array
/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 ();
}

Description: These two functions are to read the picture information.
2.3 Custom Listpreference pop-up list options

@Override
protected void Onpreparedialogbuilder (Builder Builder) {
 super.onpreparedialogbuilder (Builder);

 Iconadapter adapter = new Iconadapter (mcontext);
 Builder.setadapter (adapter, null);


Description: Click Listpreference, will pop up a list dialog box. by rewriting Onpreparedialogbuilder (), we can customize the pop-up List dialog box. This is shown by Iconadapter.

public class Iconadapter extends baseadapter{private layoutinflater minflater;
 Public Iconadapter {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.REQUESTFO
    Cus ();

    Selected effect Fholder.layout.setBackgroundColor (Color.cyan);
    Update mposition mposition = FPOs;
    Update summary IconListPreference.this.setSummary (Mentries[fpos]);
    IconListPreference.this.setIcon (Mentryicons[fpos]);
    Update the value saved by the Listpreference meditor.putstring (Mkey, mentryvalues[fpos].tostring ());

    Meditor.commit ();
   Cancels the Listpreference Settings dialog Getdialog (). dismiss ();

  }
  });
 return convertview;
  }//Listpreference each corresponding 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 through the layout icon_adapter.xml. Below look at the source code of 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:layo Ut_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 "Andro Id: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>

 

At this point, the custom listpreference is complete. Here's how to use it.
3. Use this custom listpreference
We use this custom listpreference through preferencefragment. The contents of the
3.1 preferencefragment configuration file
Res/xml/preferences.xml are as follows:

<preferencescreen xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:iconlistpreference= "http:/
  /schemas.android.com/apk/res/com.skw.fragmenttest "> <!--system default Listpreference--> <preferencecategory
   Android:title= "Preferencecategory a" > <!--(a) Android:key is Preferece's ID (s) android:title is a big title for Preferece (Android:summary) is a preferece title Android:dialogtitle is the title of the dialog box (s) android:defaultvalue is the default value of Android: 
   Entries is a description of the items in the list (a) android:entryvalues is the value of the items in the list--> <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 "/> </preferenceca tegory> <!--custom Listpreference--> <preferencecategory android:title= "Preferencecategory B" > < !--iconlistpreference:entryiconsis a custom property--> <com.skw.fragmenttest.iconlistpreference android:key= "Icon_list_preference" android:dialogTi 
   Tle= "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> </pr

 Eferencescreen>

Note: the "system default Listpreference" and "custom listpreference (i.e. iconlistpreference)" are used in this configuration file.
Notice the "iconlistpreference:entryicons" attribute in the iconlistpreference. The previous "Iconlistpreference" and the namespace of the file represent "xmlns:iconlistpreference=" http://schemas.android.com/apk/res/ Com.skw.fragmenttest "in the same iconlistpreference!" And Entryicons is our custom attribute name.
3.2 Custom Preferencefragment code

public class Prefsfragment extends Preferencefragment {

 @Override public
 void OnCreate (Bundle Savedinstancestate) {
  super.oncreate (savedinstancestate);

  Addpreferencesfromresource (r.xml.preferences);
 }

 ...
}

4. Use of Prefsfragment
below, you can use the prefsfragment in an activity.
4.1 Code to use Prefsfragment activity

public class Fragmenttest extends activity {

 @Override public
 void OnCreate (Bundle savedinstancestate) {
  Super.oncreate (savedinstancestate);
  Setcontentview (r.layout.main);

  Get Fragmentmanager
  Fragmentmanager Fragmentmanager = Getfragmentmanager ();
  Get fragmenttransaction  
  fragmenttransaction fragmenttransaction = fragmentmanager.begintransaction ();

  Prefsfragment fragment = new Prefsfragment ();
  Add the fragment to the container frag_example
  fragmenttransaction.add (r.id.prefs, fragment);
  Fragmenttransaction.commit ();
 } 


4.2 Configuration Files using prefsfragment activity
The contents of Res/layout/main.xml are as follows:

<?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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.