"Sail Plan 031" 2015 sail plan Android Apidemo Devil's pace with app->preferences->advanced Preferences custom preference Onpreferencechangelistener

Source: Internet
Author: User

Previous article Android Apidemo sample resolution: App->preferences->launching Preferences uses advanced Preferences The advancedpreferences defined in the.

This article describes Advancedpreferences, which is referred to as advanced because it involves a custom preference and refreshes the value of a preference in a worker thread.

Preference is a base class that displays in Preferenceactivity (typically shown in a list) in a preference. A bit similar to a view displayed in the activity. Preference actually accesses an item in the shared preferences, and the key defined by Preference is the key value used to access the shared preferences.

As with view, you can customize the view, and you can customize the preference in Android to show the program preferences that govern your app's customizations. This example mypreference a custom preference to store the number of times the user clicked the preference, the type is an integer, and the initial value is defined as 100. It corresponds to the definition in Advanced_preferences.xml as follows:

    <com.example.android.apis.preference.MyPreference            android:key= "My_preference"            android: Title= "@string/title_my_preference"            android:summary= "@string/summary_my_preference"             Android:defaultvalue= "/>"

Preference defines a number of attributes, such as Default Value, dependency, enabled, icon, key, and so on, with a corresponding method to operate. and provides two Listener:preferencechangelistener, Preferenceclicklistener, allows the application to respond to preference value change events, or the user clicks the preference event.

Here's a description of how to customize a preference in the Mypreference code order.

1. Derived from the preference base class.

 Public class extends Preference

2. Similar to Custom view, you can customize layout for custom preference. Mypreference uses r.layout.preference_widget_mypreference, the definition is simply a textview with an ID of mypreference_widget. You typically use Setwidgetlayoutresource to set the layout resource for a preference derived class in a constructor.

    // The constructor called by the Inflater     Public mypreference (Context context, AttributeSet attrs) {        Super(context, attrs);        Setwidgetlayoutresource (r.layout.preference_widget_mypreference);    }

3. If you need to set properties for the view in your custom layout, you can do so in Onbindview (view view). The following code sets the value for TextView to Mclickcounter.

    @Override    protectedvoid  Onbindview (view view) {        super . Onbindview (view);         // Set Our custom views inside the layout        Final TextView Mytextview = (TextView) View.findviewbyid (r.id.mypreference_widget);         if NULL ) {            mytextview.settext (string.valueof (Mclickcounter));        }    }

4. If the initial value is defined for the custom preference in XML, such as the initial value of Mypreference android:defaultvalue= "100″, we want to use this initial value in the code to initialize the variable mclickcounter. The Mclickcounter type is an integer that is used to hold the user's number of keystrokes.

@OverrideprotectedObject Ongetdefaultvalue (TypedArray A,intindex) {        //This preference type ' s value of type is Integer, so we read the default//Value from the attributes as an Integer.        returnA.getinteger (Index, 0); } @Overrideprotected voidOnsetinitialvalue (BooleanRestorevalue, Object DefaultValue) {        if(restorevalue) {//Restore StateMclickcounter =Getpersistedint (Mclickcounter); } Else {            //Set State            intValue =(Integer) defaultvalue; Mclickcounter=value;        Persistint (value); }    }

5 overloaded Onsaveinstancestate,onrestoreinstancestate, these two methods are used to temporarily save or restore some variable values. Before preference calls Persistint,persistboolean, persiststring, etc., the value of preference is not saved or updated in shared preferences, If the user rotates the screen at this point, causing the activity to be recreated, we need the user selection to be retained when the screen rotates, and you can use Onsaveinstancestate,onrestoreinstancestate to maintain some temporary data.

@Overrideprotectedparcelable onsaveinstancestate () {/** Suppose a client uses this preference type without persisting.         We * Must save the instance state so it's able to, for example, survive * orientation changes. */        FinalParcelable superstate =Super. Onsaveinstancestate (); if(Ispersistent ()) {//No need to save instance state since it ' s persistent            returnsuperstate; }        //Save the instance state        Finalsavedstate MyState =Newsavedstate (superstate); Mystate.clickcounter=Mclickcounter; returnMyState; } @Overrideprotected voidonrestoreinstancestate (parcelable state) {if(!state.getclass (). Equals (savedstate.class)) {            //didn ' t save State for us in onsaveinstancestate            Super. Onrestoreinstancestate (state); return; }        //Restore the instance statesavedstate MyState =(savedstate) state; Super. Onrestoreinstancestate (Mystate.getsuperstate ()); Mclickcounter=Mystate.clickcounter;    Notifychanged (); }

Where Savedstate is a subclass of Basesavedstate, which is not described in detail here, and Basesavedstate implements the Parcelable interface, borrowing the serialable on the Windows platform, Its functionality is similar to that of other platforms on the serialization feature.

6. Mypreference responds to the Click event and stores the number of keystrokes in the shared Preferences.

@Overrideprotected voidOnClick () {intNewValue = Mclickcounter + 1; //Give The client a chance to ignore this change if they deem it//Invalid        if(! callchangelistener(newvalue)) {            //They don ' t want the value to be set            return; }        //Increment CounterMclickcounter =NewValue; //Save to persistent storage (this method would make sure this//preference should be persistent, along and other useful checks)Persistint (Mclickcounter); //Data have changed, notify so UI can be refreshed!notifychanged (); }

Preference uses Persistboolean, Persistfloat, Persistint, Persistlong, persisitstring to store data in shared preferences, Because Mclickcounter is an integer, use Persistint. Notifychanged is used to inform the UI that there are data changes. Callchangelistener will call the registered Preference.onpreferencechangelistener to notify preference of changes.

Look at advancedpreferences again, the code is not very long, as follows:

 Public classAdvancedpreferencesextendsPreferenceactivityImplementsOnsharedpreferencechangelistener { Public Static FinalString key_my_preference = "My_preference";  Public Static FinalString key_advanced_checkbox_preference = "Advanced_checkbox_preference"; Privatecheckboxpreference mcheckboxpreference; PrivateHandler Mhandler =NewHandler (); /*** This was a simple example of controlling a preference from code. */    PrivateRunnablemforcecheckboxrunnable=NewRunnable () { Public voidrun () {if(Mcheckboxpreference! =NULL) { mcheckboxpreference.setchecked ( ! mcheckboxpreference.ischecked ()); }            //Force Toggle again in a secondMhandler.postdelayed ( This, 1000);    }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Load the XML preferences fileAddpreferencesfromresource (r.xml.advanced_preferences); //Get A reference to the checkbox preferenceMcheckboxpreference =(checkboxpreference) Getpreferencescreen (). Findpreference (key_advanced_checkbox_preference); } @Overrideprotected voidOnresume () {Super. Onresume (); //Start The Force toggleMforcecheckboxrunnable.run (); //Set up a listener whenever a key changes        Getpreferencescreen (). Getsharedpreferences (). Registeronsharedpreferencechangelistener (  This); } @Overrideprotected voidOnPause () {Super. OnPause (); //Unregister the listener whenever a key changes        Getpreferencescreen (). Getsharedpreferences (). Unregisteronsharedpreferencechangelistener (  This);    Mhandler.removecallbacks (mforcecheckboxrunnable); }     Public voidonsharedpreferencechanged (sharedpreferences sharedpreferences, String key) {//Let's do something when my counter preference value changes        if(Key.equals (key_my_preference)) {Toast.maketext ( This, "thanks! You increased my count to "+ sharedpreferences.getint (key, 0), Toast.length_short). Show (); }    }}

It implements Onsharedpreferencechangelistener, so it can be used to monitor changes in mypreference.

Handler, because the program needs to update the preference value from the worker thread, and preference is the UI, it is not possible to update the UI directly from the worker thread, allowing the worker thread to update it, which is described in detail later. This example changes the value of haunted preference once every 1 seconds (selected, not selected, not selected).

Registeronsharedpreferencechangelistener,unregisteronsharedpreferencechangelistener used for Sharedpreferences Registers a total preference Change event handling code. In this example, the number of times the current button is displayed on the screen when the mypreference changes:

"Sail Plan 031" 2015 sail plan Android Apidemo Devil's pace with app->preferences->advanced Preferences custom preference Onpreferencechangelistener

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.