Android study note 12. An in-depth understanding of LauncherActvity: LauncherActivity, PreferenceActivity, and PreferenceFragment

Source: Internet
Author: User

Android study note 12. An in-depth understanding of LauncherActvity: LauncherActivity, PreferenceActivity, and PreferenceFragment
For more information, see LauncherActivity, PreferenceActivity, and PreferenceFragment of LauncherActvity. LauncherActivity and PreferanceActivity all inherit from ListActivity. LauncherActivity is enabled when the list item is clicked; preferanceActivity implements an Activity list interface for setting and storing program parameters.
I. LauncherActivity Usage Details 1. Overview: LauncherActivity is used to develop a list interface Activity, but this list interface is different from a common list interface. Each list item in the developed list interface corresponds to an Intent, and different intents are returned according to different lists by rewriting the intentForPosition (int position) method. When you click different list items, the application automatically starts the corresponding Acitviy. The effect is as follows:
2. Introduction to the LauncherActivity class(1) constructor: LauncherActivity () (2) Important Method Intent intentForPosition (int position): return different intent void onCreate (Bundle savedInstanceState) based on different lists ): the first void onListItemClick (ListView l, View v, int position, long id) is called to start an Activity. This method is called when a list item is clicked. (3) Intent constructor: intent () Intent (Intent o) Intent (String action, Uri uri) Intent (Context packageContext, Class Cls) Intent (String action, Uri uri, Context packageContext, Class Cls)3. Development Ideas and source code(1) Fill in the list item content for the LauncherActivity interface. Assemble the array string data source to the view through the Assembly adapter, and according to the android. r. layout. simple_expandable_list_item_1 layout file design the appearance and content of each list item; String [] names = {set program parameters, view race}; ArrayAdapter Adapter = new ArrayAdapter (This, android. R. layout. simple_expandable_list_item_1, names); setListAdapter (adapter );
(2) override the Intent intentForPosition (int position) method to return different intent values based on different lists. When you click an Activity list item, the system will pass the position parameter of the item to the intentForPosition method, and return an intent to the context interface to start the corresponding acitent. Class [] Classes = {PreferenceActivityTest. class, ExpandableListActivityTest. class}; public Intent intentForPosition (int position) {return new Intent (LaunchActivity. this, classes [position]); // a new intent} (3) implements the Acitvity corresponding to the intent, which can inherit from Activity, PreferenceActivity, ExpandableListActivity, and so on.

(3) source code

Package com. example. android_activity_1; import android. app. launcherActivity; import android. content. intent; import android. OS. bundle; import android. widget. arrayAdapter;/* main Activity: LauncherActivity * Each list item corresponds to an Intent **/public class LaunchActivity extends LauncherActivity {// 1. define the names of two activities: String [] names = {set program parameters, view race}; // 2. defines the implementation classes corresponding to two activities. The former is used to display a window for displaying the set Option parameters and saving them. The latter is used to display an expandable List window (Activity) Class.
 [] Classes = {PreferenceActivityTest. class, ExpandableListActivityTest. class}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // 3. assemble the ArrayAdapter adapter and assemble the data to the ArrayAdapter in the corresponding list item view.
 
  
Adapter = new ArrayAdapter
  
   
(This, android. r. layout. simple_expandable_list_item_1, names); // 4. set the adapter setListAdapter (adapter) required for the list displayed in this window;} // 5. override Intent IntentForPosition (int position) method: the intent returned by the list item is used to start different activities public Intent intentForPosition (int position) {return new Intent (LaunchActivity. this, classes [position]); // returns an Intent object, indicating the class to be started. The position value is determined when the user clicks the list item in the Activity }}
  
 


Ii. Usage of PreferenceActivity
1. Overview: PreferenceActivity is a very useful base class. When an Android application needs to set options and want these options to be saved as parameters, we can implement PreferenceActivity. PreferenceActivity is different from an ordinary Acitvity. It does not use an ordinary interface layout file, but uses an option-based layout file. Option setting layout file: PreferenceScreen is used as the root element, which indicates defining the interface layout of a parameter setting. In addition, once an Activity inherits PreferenceActivity, the Activity does not need to control its own Preferences read/write. PreferenceActivity will handle all this for us. 2. Introduction to the PreferenceActivity class(1) Embedding class: class PreferenceActivity. Header: Used DescriptionThe user will click Header list item(2) important methods of PreferenceActivity public void loadHeadersFromResource (int resid, List
Target) function: parse the layout resource file represented by resid, according to the element
 
  
Add a header (list item) to the target list. Public void onBuildHeaders (List
  
Target) function: loads the page layout file to the Activity. This method adds at least one header to the Activity list and enables acitment to run in its fragment mode. Here, List
A List set is used to store the headers in the layout file. Call loadHeadersFromResource (R. layout. *, list) to add the layout resource to the List dataset.3. Development Ideas and source codeTo create a PreferenceActivity interface, you must first create a corresponding interface layout file. Starting from Android3.0, we officially recommend combining PreferenceActivity with PreferenceFragment to implement the parameter setting interface. PreferenceActivity is only responsible for loading the layout file (A) of the option setting list; PreferenceFragment is responsible for loading the layout file (B) of the option setting list )).
(1) PreferenceActivity loading option sets the layout file of the list. Its root element is
...The element of each list item is
     

     Or
     
      
, As shown in (.
      
// Implement a list item
Android: icon = // specify the list item icon
Android: title = // specify the title of the list item
Android: summary => // specifies the description of the list items.
To pass data to the Prefs1Fragment interface (Activity), that is, website = www.baidu.com
Android: value = www.baidu.com/> , Start an Activity android: action = android. intent. action. VIEW
Android: data = http://www.baidu.com/> ................
Android: fragment specifies the preferenceFragment interface to be started by the list item. The format is: package. Class. $ internal class. This internal class inherits from PreferenceFragment. Get input in Prefs1Fragment The Fragment parameter: String website = getArguments (). getString (website); Toast. makeText (getActivity (), website Domain Name: + website, Toast. LENGTH_SHORT ). show ();
  Source code res/layout/preference. xml:The layout defines three list items. The first two list items use the android: fragment attribute to specify the PreferenceFragment for the startup response. The third list item uses The child element starts the specified Activity.
           

(2) implement a PreferenceActivity (PreferenceActivityTest. java), mainly to complete two tasks:. load the layout file (res/layout/preference. xml) to PreferenceActivity, by rewriting its public void onBuildHeaders (List Target) method implementation; public void onBuildHeaders (List Target) {super. loadHeadersFromResource (R. layout. preference, target);} B. defines the PreferenceFragment internal class used in the layout file of the implementation option setting list; public static class Prefs1Fragment extends PreferenceFragment {public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); addPreferencesFromResource (R. xml. preferences); // load the option to set the layout file to PreferenceFragment }}
Source code src/package name/PreferenceActivityTest. java:
Package com. example. android_activity_1; import java. util. list; import android. OS. bundle; import android. preference. preferenceActivity; import android. preference. preferenceFragment; import android. widget. button; import android. widget. toast;/* PreferenceActivity: * use PreferenceFragment to set parameters. * PreferenceFragment is used to load the layout file set for options; preferenceActivity is responsible for loading the layout file */public class PreferenceActivityTest extends PreferenceActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // 1. this method is used to set the title Button if (hasHeaders () {button Button button = new Button (this); button. setText (set operation); // Add the button to the interface setListFooter (button) ;}// 2. this method loads the page layout file @ Override public void onBuildHeaders (List
Target) {// TODO Auto-generated method stub super. loadHeadersFromResource (R. layout. preference, target);} // 3. the Prefs1Fragment and Prefs2Fragment internal classes public static class Prefs1Fragment extends {@ Override public void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); addPreferencesFromResource (R. xml. preferences); // load the option to set the layout file to PreferenceFragment} public static class Prefs2Fragment extends PreferenceFragment {@ Override public void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); addPreferencesFromResource (R. xml. display_prefs); // load the option to set the layout file to PreferenceFragment // obtain the parameter String website = getArguments () that is passed in the Fragment (). getString (website); Toast. makeText (getActivity (), website Domain Name: + website, Toast. LENGTH_SHORT ). show ();}}}
(3) create the option settings parameter layout file display_prefs.xml and preferences. xml options to set the parameter layout file
Is the root element. For each item of option parameters, we can construct our own option Setting Parameter groups through the properties provided by the system to implement the expected functions.

Source code res/xml/preferences. xml
               
 
 
                       
                 
 
                  
                  Source code res/xml/display_prefs.xml
                  
 
                   
                   
 
                     
                      
                     
                     
 
                      
                       

Note: The preceding interface layout file defines a parameter setting interface, which contains two parameter setting groups. Once the interface layout file for parameter settings is defined, addPreferencesFromResource (R. xml. preferences) is called in PreferenceFragment. The layout file for option settings is loaded to PreferenceFragment. (1) android: key attributes: (2) res/values/array Dark Bright Brightest 1 2 3 (4) modify the AndroidManifest. xml project file to configure and manage the preceding three activities. Add the ExpandableListActivityTest and PreferenceActivityTest interfaces to the list file.
                     
                          
                      
                     

Summary: The preceding application uses PreferenceActivity to generate the option setting list interface; PreferenceFragment to generate the option setting interface (B )). PreferenceActivity is used to set the application option parameters. The system automatically saves the set parameters permanently to the system. For example, if you click Enter User Name List in the settings option, the program automatically saves the set Option parameters to the mobile phone/data/<application package name>/pai_prefs path, the file name is <application package name> _ preferences. xml.Iii. Explanation of PreferenceFragmentIn android applications, the setting function is usually used to set global options, such as font color and personal preferences. These items are all in xml, and the corresponding object in android is SharedPreferences. PreferenceFragment or PreferenceActivity it is obvious that PreferenceFragment is Fregment and PreferenceActivity is Activity. When your application targets more than 3.0 of the system, you should use PreferenceFragment. If the mainstream system is 4.0, you should choose PreferenceFragment. The reason is that PreferenceFragment is a smoother structure. You can attach it to any activity. Google strongly recommends PreferenceFragment! Frequently Used Preference CheckPreference -- CheckBox single comment EditTextPreference -- EditText input text box ListPreference -- ListView list box RingtonePreference -- select the ringtone XML definition common attributes include: android: key: Unique "ID" of each Preference control ", this Preference is unique. Android: defaultValue: default value. For example, the default value of CheckPreference can be "true", the default value is selected, and the default value of EditTextPreference can be "110 ". Android: enabled: indicates whether the Preference is available. Android: title: The title displayed by each Preference on the PreferenceScreen layout -- big title android: summary: The title displayed by each Preference on the PreferenceScreen layout -- subtitle (may not be) in ListPreference: android: entries: array type. The android: entryValues: Type of the text to be displayed by the control is array. The key-value pair corresponding to the text is saved to the sharedPreference file.
Step 2 of PreferenceFragment) 1. Define preference create a preferences. xml in res/xml of the project to define the setting options on the menu interface.(Android: entries and android: entryValues are defined in res/values/strings. xml)2. Create an activity for PreferenceFragmentAttachment
  1. PackageCom. example. androidpreferencefragment;
  2.  
  3. ImportAndroid. app. Activity;
  4. ImportAndroid. OS. Bundle;
  5.  
  6. Public ClassSetPreferenceActivityExtendsActivity {
  7.  
  8. @ Override
  9. Protected VoidOnCreate (Bundle savedInstanceState ){
  10. // TODO Auto-generated method stub
  11. Super. OnCreate (savedInstanceState );
  12.  
  13. GetFragmentManager (). beginTransaction (). replace (android. R. id. content,
  14. NewPrefsFragment (). commit ();
  15. }
  16.  
  17. }3. Create PreferenceFragment.Implements OnSharedPreferenceChangeListener is used to monitor whether SharedPreference changes. The main function here is to promptly update the summary of the preference on the interface when SharedPreference changes to provide a better interaction. Note that you must register and uninstall listeners in OnResume and OnPause to maintain the lifecycle of the activity. Note: you cannot set OnChangeListener for each preference to update the summary of the preference on the interface. This will prevent the system from storing preference. xml.
    1. PackageCom. example. androidpreferencefragment;
    2.  
    3. ImportAndroid. annotation. SuppressLint;
    4. ImportAndroid. content. SharedPreferences;
    5. ImportAndroid. content. SharedPreferences. OnSharedPreferenceChangeListener;
    6. ImportAndroid. OS. Bundle;
    7. ImportAndroid. preference. Preference;
    8. ImportAndroid. preference. PreferenceFragment;
    9. ImportAndroid. preference. Preference. OnPreferenceChangeListener;
    10.  
    11. @ SuppressLint (NewApi)
    12. Public ClassPrefsFragmentExtendsPreferenceFragmentImplementsOnSharedPreferenceChangeListener {
    13.  
    14. @ Override
    15. Public VoidOnCreate (Bundle savedInstanceState ){
    16. // TODO Auto-generated method stub
    17. Super. OnCreate (savedInstanceState );
    18.  
    19. // Load the preferences from an XML resource
    20. AddPreferencesFromResource (R. xml. preferences );
    21. }
    22.  
    23. @ Override
    24. Public VoidOnSharedPreferenceChanged (SharedPreferences sharedPreferences, String key ){
    25. // TODO Auto-generated method stub
    26. // Set summary to be the user-description for the selected value
    27. If(! Key. equals (MainActivity. PRF_CHECK ))
    28. {
    29. Preference connectionPref = findPreference (key );
    30. ConnectionPref. setSummary (sharedPreferences. getString (key ,));
    31. }
    32. }
    33.  
    34. @ Override
    35. Public VoidOnResume (){
    36. Super. OnResume ();
    37. GetPreferenceManager (). getSharedPreferences (). registerOnSharedPreferenceChangeListener (This);
    38.  
    39. }
    40.  
    41. @ Override
    42. Public VoidOnPause (){
    43. GetPreferenceManager (). getSharedPreferences (). unregisterOnSharedPreferenceChangeListener (This);
    44. Super. OnPause ();
    45. }
    46.  
    47. }4. Set the default valueWhen the user runs the application for the first time, the user has not set his/her preference. In this case, the default prefernnce must be specified.

      First, define the android: defaultValue in xml. Then, call the setdefavaluvalues method in the onCreate method of the main Activity (or another activity, but it will definitely go in during the first running, for example, the pop-up Activity.

      1. PreferenceManager. setDefaultValues (This, R. xml. preferences,False);

        This function has three parameters:

        The first is the application context, the second is the preference id, and the third is false, which means to load the default value only at the first run.

        5. Retrieve the preference value

         

        SharedPreferences mySharedPreferences = PreferenceManager. getdefasharsharedpreferences (This); Then the get method and key value can be used to retrieve the corresponding value, for example:

         

        Boolean my_checkbox_preference = mySharedPreferences. getBoolean (checkbox_preference, false );

        String my_edittext_preference = mySharedPreferences. getString (edittext_preference,); reference: http://blog.csdn.net/silangquan/article/details/11022335

         

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.