Explain the use of the Android preference framework in detail

The term preference will 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 for handling preferences. It provides simple API to hide preference reading and persistence, and provides an elegant preferences interface.

First, let’s look at the preferences interface of the software below:

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

CheckBoxPreference : used to turn on or off a function

ListPreference : used to select a value from multiple options;

EditTextPreference : used to configure a piece of text information;

Preference : Used to perform related custom operations (clear cache, history, form, and cookie in the above figure all belong to this item);

RingtonePreference : It is 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 , which will record the latest configuration information.

So how to use the preferred framework? We need the following steps:

1. Create a preference xml configuration file and place it under the /res/xml directory of the project;

2. Create a new Activity, inherit android.preference.PreferenceActivity , and then load our preference configuration file in the onCreate method.

Next, I will demonstrate the configuration and use of the preference framework for you:

We create a new prefs project, the project structure is as follows:

The function we want to achieve is very similar to that of the above software. Let me explain the overall process of this project:

1. Main interface. Display user nickname, there are three parameters, nickname text, font size and background color. When entering for the first time, use the default value.

2. Press the settings item in the menu button to jump to the preference page for parameter selection.

3. Press the return key to return to the main interface, and the set parameters will take effect.

First, let's take a look at the configuration file of the main interface, which is very simple, just a TextView:

  1. <? xml   version = "1.0"   encoding = "utf-8" ?>   
  2. < LinearLayout   xmlns:android = "http://schemas.android.com/apk/res/android"   
  3.     android:orientation = "vertical"   
  4.     android:layout_width = "fill_parent"   
  5.     android:layout_height = "fill_parent" >   
  6.     < TextView   
  7.         android:id = "@+id/textView"   
  8.         android:layout_width = "fill_parent"   
  9.         android:layout_height = "fill_parent"   
  10.         android:gravity = "center_horizontal"   
  11.         android:textColor = "#FF0000" />   
  12. </ LinearLayout >   

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

  1. package  com.scott.prefs;  
  2.   
  3. import  android.app.Activity;  
  4. import  android.content.Context;  
  5. import  android.content.Intent;  
  6. import  android.content.SharedPreferences;  
  7. import  android.graphics.Color;  
  8. import  android.os.Bundle;  
  9. import  android.view.Menu;  
  10. import  android.view.MenuItem;  
  11. import  android.widget.TextView;  
  12.   
  13. public   class  MainActivity  extends  Activity {  
  14.       
  15.     private   static   final   int  SETTINGS_ID =  0 ;  
  16.     private   static   final   int  EXIT_ID =  1 ;  
  17.       
  18.     private  TextView textView;  
  19.       
  20.     @Override   
  21.     public   void  onCreate(Bundle savedInstanceState) {  
  22.         super .onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.         textView = (TextView) findViewById(R.id.textView);  
  25.         showSettings();  
  26.     }  
  27.       
  28.     @Override   
  29.     public   boolean  onCreateOptionsMenu(Menu menu) {  
  30.         super .onCreateOptionsMenu(menu);  
  31.         menu.add(0 , SETTINGS_ID,  0"Settings" );  
  32.         menu.add(0 , EXIT_ID,  0"Quit" );  
  33.         return   true ;  
  34.     }  
  35.       
  36.     @Override   
  37.     public   boolean  onOptionsItemSelected(MenuItem item) {  
  38.         if  (item.getItemId() == SETTINGS_ID) {  
  39.             Intent intent = new  Intent(MainActivity. this , PrefsActivity. class );  
  40.             //If requestCode >= 0, the onActivityResult() method will be called back when the result is returned   
  41.             startActivityForResult(intent, 1 );  
  42.         } else  {  
  43.             finish();  
  44.         }  
  45.         return   true ;  
  46.     }  
  47.       
  48.     @Override   
  49.     protected   void  onActivityResult( int  requestCode,  int  resultCode, Intent data) {  
  50.         super .onActivityResult(requestCode, resultCode, data);  
  51.         showSettings();  
  52.     }  
  53.   
  54.     private   void  showSettings() {  
  55.         String prefsName = getPackageName() + "_preferences" ;    //[PACKAGE_NAME]_preferences   
  56.         SharedPreferences prefs = getSharedPreferences(prefsName, Context.MODE_PRIVATE);  
  57.   
  58.         String nickName = prefs.getString( "nickName""robot" );  
  59.         textView.setText( "Welcome:"  + nickName);  
  60.           
  61.         boolean  nightMode = prefs.getBoolean( "nightMode"false );  
  62.         textView.setBackgroundColor(nightMode ? Color.BLACK : Color.WHITE);  
  63.           
  64.         String textSize = prefs.getString("textSize""0" );  
  65.         if  (textSize.equals( "0" )) {  
  66.             textView.setTextSize(18f);  
  67.         } else   if  (textSize.equals( "1" )) {  
  68.             textView.setTextSize(22f);  
  69.         } else   if  (textSize.equals( "2" )) {  
  70.             textView.setTextSize(36f);  
  71.         }  
  72.     }  
  73. }  

It can be seen that after entering the main interface, the preference configuration information will be obtained according to [PACKAGE_NAME]_preferences. If it is the first time to enter, the default value will be used. The following is the screen when we enter the main interface for the first time:

It can be seen that when we first entered the interface, the nickname was "Robot", the background of the characters was white, and the size of the characters was 18 points.

Then after pressing Settings, we can configure the preferences. Let's take a look at the configuration of settings.xml:

  1. <? xml   version = "1.0"   encoding = "utf-8" ?>   
  2. < PreferenceScreen   xmlns:android = "http://schemas.android.com/apk/res/android"   
  3.     android:key = "settings"   
  4.     android:title = "Software Settings" >   
  5.     < PreferenceCategory   
  6.         android:key = "basic"   
  7.         android:title = "Basic Settings" >   
  8.         < EditTextPreference   
  9.             android:key = "nickName"   
  10.             android:title = "Nickname"   
  11.             android:defaultValue = "robot" />   
  12.         < CheckBoxPreference   
  13.             android:key = "nightMode"   
  14.             android:title = "Night Mode"   
  15.             android:summaryOn = "Enabled"   
  16.             android:summaryOff = "Not enabled" />   
  17.         < ListPreference   
  18.             android:key = "textSize"   
  19.             android:title = "Text Size"   
  20.             android:dialogTitle = "Text Size"   
  21.             android:entries = "@array/textSize_entry"   
  22.             android:entryValues = "@array/textSize_entry_value"   
  23.             android:defaultValue = "0" />   
  24.     </ PreferenceCategory >   
  25.     < PreferenceCategory   
  26.         android:key = "clean"   
  27.         android:title = "Clear Records" >   
  28.         < Preference    
  29.             android:key = "cleanHistory"   
  30.             android:title = "Clear History"   />       
  31.     </ PreferenceCategory >   
  32. </ PreferenceScreen >   

Among them, the outermost layer is the PreferenceScreen tag, which represents a collection of preferences; then, we noticed the item PreferenceCategory , which represents a category and can contain multiple preferences; the last is the preference we use to configure parameters up. What needs to be understood is that PreferenceScreen can also be nested , which means that the above PreferenceCategory can be replaced by PreferenceScreen.

In addition, we also need to understand several common tag attributes that appear in the file:

  The name or key of the android:key option

  The title of the android:title option

  A short summary of the android:summary option

The text of the android:entries   list item

  The value of each item in the android:entryValues ​​list

android:dialogTitle   dialog box title

  The default value of the options in the android:defaultValue list

There are two special properties for CheckBoxPreference

  The summary displayed when the android:summaryOn option is selected

  The summary displayed when the android:summaryOff option is unchecked

We can also see that in ListPreference, entries come from textSize_entry, and entryValues ​​comes from textSize_entry_value, both of which are configured in text_size.xml in the /res/values ​​directory:

  1. <? xml   version = "1.0"   encoding = "utf-8" ?>   
  2. < resources >   
  3.     < string-array   name = "textSize_entry" >   
  4.         < item ></ item >   
  5.         < item ></ item >   
  6.         < item ></ item >   
  7.     </ string-array >   
  8.     < string-array   name = "textSize_entry_value" >   
  9.         < item > 0 </ item >   
  10.         < item > 1 </ item >   
  11.         < item > 2 </ item >   
  12.     </ string-array >   
  13. </ resources >   

After the configuration is complete, we are left with the last step, creating an Activity, inheriting PreferenceActivity, loading the preference resource file, and processing the corresponding option event.

PrefsActivity.java code is as follows:

  1. package  com.scott.prefs;  
  2.   
  3. import  android.app.AlertDialog;  
  4. import  android.content.DialogInterface;  
  5. import  android.os.Bundle;  
  6. import  android.preference.EditTextPreference;  
  7. import  android.preference.ListPreference;  
  8. import  android.preference.Preference;  
  9. import  android.preference.PreferenceActivity;  
  10. import  android.preference.PreferenceScreen;  
  11. import  android.widget.Toast;  
  12.   
  13. public   class  PrefsActivity  extends  PreferenceActivity  implements  Preference.OnPreferenceChangeListener {  
  14.   
  15.     private  EditTextPreference nickName;  
  16.     private  ListPreference textSize;  
  17.     private  Preference cleanHistory;  
  18.   
  19.     @Override   
  20.     public   void  onCreate(Bundle savedInstanceState) {  
  21.         super .onCreate(savedInstanceState);  
  22.         addPreferencesFromResource(R.xml.setttings);  
  23.         nickName = (EditTextPreference) findPreference("nickName" );  
  24.         textSize = (ListPreference) findPreference("textSize" );  
  25.         cleanHistory = findPreference("cleanHistory" );  
  26.           
  27.         //Register Preference.OnPreferenceChangeListener listener event for nickName and textSize   
  28.         // We can update the summary immediately when the value changes   
  29.         nickName.setOnPreferenceChangeListener(this );  
  30.         textSize.setOnPreferenceChangeListener(this );  
  31.           
  32.         initSummary();  
  33.     }  
  34.       
  35.     //Initialize summary   
  36.     private   void  initSummary() {  
  37.         nickName.setSummary(nickName.getText());  
  38.           
  39.         setTextSizeSummary(textSize.getValue());  
  40.     }  
  41.       
  42.     private   void  setTextSizeSummary(String textSizeValue) {  
  43.         if  (textSizeValue.equals( "0" )) {  
  44.             textSize.setSummary("小" );  
  45.         } else   if  (textSizeValue.equals( "1" )) {  
  46.             textSize.setSummary("中" );  
  47.         } else   if  (textSizeValue.equals( "2" )) {  
  48.             textSize.setSummary("大" );  
  49.         }  
  50.     }  
  51.   
  52.     /**  
  53.      * Rewrite the onPreferenceTreeClick method of PreferenceActivity  
  54.      * When the preference is clicked, make corresponding processing operations  
  55.      */   
  56.     @Override   
  57.     public   boolean  onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {  
  58.         if  (preference == cleanHistory) {  
  59.             new  AlertDialog.Builder( this )  
  60.                     .setTitle( "Clear History" )  
  61.                     .setMessage( "Do you really want to clear the history?" )  
  62.                     .setPositiveButton("是"new  DialogInterface.OnClickListener() {  
  63.                         @Override   
  64.                         public   void  onClick(DialogInterface dialog,  int  which) {  
  65.                             //cleaning history...   
  66.                             Toast.makeText(PrefsActivity.this "Clear Successfully" , Toast.LENGTH_SHORT).show();  
  67.                         }  
  68.                     }).setNegativeButton("否"new  DialogInterface.OnClickListener() {  
  69.                         @Override   
  70.                         public   void  onClick(DialogInterface dialog,  int  which) {  
  71.                             dialog.dismiss();  
  72.                         }  
  73.                     }).create().show();  
  74.         }  
  75.         return   true ;  
  76.     }  
  77.       
  78.     /**  
  79.      * Rewrite the onPreferenceChange method of Preference.OnPreferenceChangeListener  
  80.      * When the value of the preference changes, make corresponding operations  
  81.      */   
  82.     @Override   
  83.     public   boolean  onPreferenceChange(Preference preference, Object newValue) {  
  84.         if  (preference == nickName) {  
  85.             nickName.setSummary(newValue.toString());  
  86.         } else   if  (preference == textSize) {  
  87.             setTextSizeSummary(newValue.toString());  
  88.         }  
  89.         return   true ;  
  90.     }  
  91. }  

Finally, don't forget to add this Activity configuration information in AndroidManifest.xml:

  1. < activity   android:name = ".PrefsActivity" />   

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

After the above steps, our preference configuration is complete, and the interface entered for the first time is as follows:

Then we change the nickname, night mode, and text size respectively, as follows:

It can be seen that after we change the value of the option, the summary part has been set to the latest value. At this time, a com.scott.prefs_preferences.xml file is generated in the shared_prefs directory under our application, as shown in the figure:

The content is as follows:

  1. <? xml   version = '1.0'   encoding = 'utf-8'   standalone = 'yes'   ?>   
  2. < map >   
  3. < boolean   name = "nightMode"   value = "true"   />   
  4. < string   name = "nickName" > scott </ string >   
  5. < string   name = "textSize" > 2 </ string >   
  6. </ map >   

At this point, we press the back button to return to the main interface, and find that the settings just now have taken effect:

It can be seen that the nickname has been changed to "scott", the background of the characters has been changed to black, and the size of the characters has been changed to 36 points.

If we press Clear History on the preferences interface, the following interface will appear:

Guess you like

Origin blog.csdn.net/cz285933169/article/details/6528852