Detailed examples of Android preference Framework usage _android

Source: Internet
Author: User

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.

First, let's look at the preferences interface for the following software:

The software uses several types of preferences, each of which has its own unique usage, and let's take a look at a few common preferences:

    • Checkboxpreference: Used to turn a feature on or off
    • Listpreference: Used to select a value from multiple options;
    • Edittextpreference: Used to configure a piece of text information;
    • Preference: Used to perform related custom actions (the purge cache, history, form, cookie in the image above);
    • 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 how do you use the preferred frame of mind? We need the following steps:

1. Create a preference XML configuration file, placed under the project's/res/xml directory;

2. Create a new activity, inherit android.preference.PreferenceActivity, and then load our preferences profile in the OnCreate method.

Next, I'll show you how to configure and use the preferences framework:

We create a new Prefs project with the following project structure:

The function we want to implement is similar to that of the software above, let me explain the whole process of the project:

1. Main interface. Displays the user's nickname, with three parameters, nickname text, font size, and background color. The default value is used when first entered.

2. Press the Settings item in the menu key to jump to the preferences page for parameter selection.

3. Press the return key, return to the main interface, set the parameters into effect.

First, let's take a look at the configuration file for the main interface, very simple, just a textview:

<?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" > 
  <textview 
    android:id= "@+id/textview" android:layout_width= "Fill_parent" 
    " 
    android:layout_height=" fill_parent " 
    android:gravity=" center_horizontal " 
    android:textcolor=" FF0000 "/> 

Then, we need to set the TextView appearance and background in the main interface according to the configuration parameters, Mainactivity.java code as follows:

Package com.scott.prefs; 
Import android.app.Activity; 
Import Android.content.Context; 
Import android.content.Intent; 
Import android.content.SharedPreferences; 
Import Android.graphics.Color; 
Import Android.os.Bundle; 
Import Android.view.Menu; 
Import Android.view.MenuItem; 
 
Import Android.widget.TextView; 
  public class Mainactivity extends activity {private static final int settings_id = 0; 
 
  private static final int exit_id = 1; 
 
  Private TextView TextView; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    TextView = (TextView) Findviewbyid (R.id.textview); 
  Showsettings (); 
    @Override public boolean Oncreateoptionsmenu (Menu menu) {super.oncreateoptionsmenu (menu); 
    Menu.add (0, settings_id, 0, "SETTINGS"); 
    Menu.add (0, exit_id, 0, "Quit"); 
  return true; @Override public boolean onoptionsitemselected (MenuItem item) {IF (item.getitemid () = = settings_id) {Intent Intent = new Intent (mainactivity.this, Prefsactivity.class); 
    If Requestcode >= 0 Returns the result, the Onactivityresult () method Startactivityforresult (Intent, 1) is recalled; 
    else {finish (); 
  return true; @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityr 
    Esult (Requestcode, ResultCode, data); 
  Showsettings ();  private void Showsettings () {String prefsname = getpackagename () + "_preferences"; 
 
    [package_name]_preferences sharedpreferences prefs = getsharedpreferences (Prefsname, Context.MODE_PRIVATE); 
    String nickname = prefs.getstring ("nickname", "Robot"); 
 
    Textview.settext ("Welcome:" + nickname); 
    Boolean nightmode = Prefs.getboolean ("Nightmode", false); Textview.setbackgroundcolor (Nightmode?) 
 
    Color.BLACK:Color.WHITE); 
    String textsize = prefs.getstring ("textsize", "0"); if (Textsize.equals ("0") {textview.settextsize (18f); 
    else if (textsize.equals ("1")) {textview.settextsize (22f); 
    else if (Textsize.equals ("2")) {textview.settextsize (36f); 
 } 
  } 
}

As you can see, after entering the main interface, you will get preference configuration information according to [Package_name]_preferences, if it is first entered, use the default value, and here is the screen when we first enter the main interface:

We can see that the first time we enter the interface nickname "Robot", the background of the word is white, the word size is 18th number.

Then, after you press the settings, we can configure the preferences, let's take a look at the settings.xml configuration:

<?xml version= "1.0" encoding= "Utf-8"?> <preferencescreen xmlns:android= "http://schemas.android.com/apk/" 
    Res/android "android:key=" Settings android:title= "Software Setup" > <preferencecategory android:key= "Basic" android:title= "Basic Settings" > <edittextpreference android:key= "nickname" android:title= "nickname" Andro id:defaultvalue= "Robot"/> <checkboxpreference android:key= "Nightmode" android:title= "Night Mode" a Ndroid:summaryon= "android:summaryoff=" is enabled/> <listpreference android:key= "Textsize" a ndroid:title= "Text Size" android:dialogtitle= "Text Size" android:entries= "@array/textsize_entry" Android:entryv alues= "@array/textsize_entry_value" android:defaultvalue= "0"/> </PreferenceCategory> <preferencec 
      Ategory android:key= "clean" android:title= "purge record" > <preference android:key= "cleanhistory" android:title= "Purge history"/>  
  </PreferenceCategory> </PreferenceScreen> 
 

Where the outermost layer is the preferencescreen tag, which represents a set of preferences, and then we notice that the Preferencecategory item, which represents a category, can contain multiple preferences, and finally the preferences we use to configure the parameters. What you need to know is that Preferencescreen can also be nested, meaning that the preferencecategory above can be replaced with Preferencescreen.

In addition, we need to look at several common tag properties that appear in the file:

    • The name or key of the Android:key option
    • Title of the Android:title option
    • Short summary of the android:summary option
    • Android:entries the text of a list item
    • Android:entryvalues the value of each item in the list
    • Android:dialogtitle dialog box title
    • Android:defalutvalue the default value for the selected item in the list
    • There are two special properties for Checkboxpreference
    • Summary displayed when the Android:summaryon option is selected
    • Summary displayed when the Android:summaryoff option is not selected

We can also see that in Listpreference, entries comes from Textsize_entry, and Entryvalues comes from Textsize_entry_value, both of which are in the/res/values directory text _size.xml configuration:

<?xml version= "1.0" encoding= "Utf-8"?> 
<resources> 
  <string-array name= "Textsize_entry" > 
    <item> Small </item> 
    <item> </item> 
    <item> big </item> 
  </ string-array> 
  <string-array name= "Textsize_entry_value" > 
    <item>0</item> 
    < item>1</item> 
    <item>2</item> 
  </string-array> 

Once the configuration is complete, we are left with the last step, creating the activity, inheriting preferenceactivity, loading the preference resource file, and handling the appropriate option events.

The Prefsactivity.java code is as follows:

Package com.scott.prefs; 
Import Android.app.AlertDialog; 
Import Android.content.DialogInterface; 
Import Android.os.Bundle; 
Import android.preference.EditTextPreference; 
Import android.preference.ListPreference; 
Import android.preference.Preference; 
Import android.preference.PreferenceActivity; 
Import Android.preference.PreferenceScreen; 
 
Import Android.widget.Toast; public class Prefsactivity extends Preferenceactivity implements Preference.onpreferencechangelistener {private Edit 
  Textpreference nickname; 
  Private Listpreference textsize; 
 
  Private preference cleanhistory; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Addpreferencesfromresource (r.xml.setttings); 
    Nickname = (edittextpreference) findpreference ("nickname"); 
    Textsize = (listpreference) findpreference ("Textsize"); 
 
    Cleanhistory = Findpreference ("Cleanhistory"); Register for nickname and Textsize Preference.onpreferencechangelisWe can update summary nickname.setonpreferencechangelistener (this) immediately when Tener Monitor Event//duty changes; 
 
    Textsize.setonpreferencechangelistener (this); 
  Initsummary (); 
 
    }//Initialize summary private void Initsummary () {nickname.setsummary (Nickname.gettext ()); 
  Settextsizesummary (Textsize.getvalue ()); } private void Settextsizesummary (String textsizevalue) {if (Textsizevalue.equals ("0")) {Textsize.setsu 
    Mmary ("small"); 
    else if (textsizevalue.equals ("1")) {textsize.setsummary ("medium"); 
    else if (Textsizevalue.equals ("2")) {textsize.setsummary ("large"); /** * Rewrite the Onpreferencetreeclick method of preferenceactivity * to handle actions when preferences are clicked * * @Override public b Oolean Onpreferencetreeclick (Preferencescreen preferencescreen, preference preference) {if (Preference = = CleanHisto RY) {new Alertdialog.builder (this). Settitle ("Purge History"). Setmessage ("Do you really want to clear history?" "). Setpositivebutton (" Yes ", New Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface dialog, I 
              NT which) {//cleaning history ... 
            Toast.maketext (Prefsactivity.this, "purge success", Toast.length_short). Show (); }). Setnegativebutton ("No", new Dialoginterface.onclicklistener () {@Override public void OnC 
        Lick (dialoginterface dialog, int which) {Dialog.dismiss (); 
    ). Create (). Show (); 
  return true;  
  /** * Rewrite the Onpreferencechange method of Preference.onpreferencechangelistener * Handle actions when the value of the preference is changed * * @Override 
      public boolean onpreferencechange (preference preference, Object NewValue) {if (preference = = nickname) { 
    Nickname.setsummary (Newvalue.tostring ()); 
    else if (preference = = Textsize) {settextsizesummary (newvalue.tostring ()); 
  return true; 
 } 
}

Finally, don't forget to include this activity configuration information in Androidmanifest.xml:

 
 

Of course we can also configure the <intent-filter></intent-filter> properties.

After a few steps, our preference configuration is complete and the first entry interface is as follows:
Then we change the nickname, night mode, text size, as follows:
As you can see, when we change the value of the option, the summary section has been set to the most recent value, and then a com.scott.prefs_preferences.xml file is generated in the Shared_prefs directory under our application, as shown in figure:

The contents are as follows:

<?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?> 
<map> 
  <boolean name= ' Nightmode ' Value= "true"/> 
  <string name= "nickname" >scott</string> 
  <string name= "Textsize" >2< /string> 

At this point, we press the rollback key, back to the main interface, found that the settings have been in effect:

As you can see, the nickname has been changed to "Scott", the background of the word has changed to black, and the word size has changed to number 36th.

If we press the Purge history entry in the Preferences interface, the interface will appear:

Original link: http://blog.csdn.net/liuhe688/article/details/6448423

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.