Android Preferences (7) custom preference, and Preferencedialog

Source: Internet
Author: User
Tags xml attribute

Building a Custom Preference

The Android framework includes a variety of subclasses that allow you to Preference build a UI for several different types of s Ettings. However, might discover a setting you need for which there ' s no built-in solution, such as a number picker or date pic Ker. In such a case, you'll need to create a custom preference by extending the class or one of the other Preference subclasses.

When you extend Preference the class, there is a few important things you need to do:

    • Specify the user interface that appears when the user selects the settings.
    • Save the setting ' s value when appropriate.
    • Initialize the With the current Preference (or default) value when it comes into view.
    • Provide the default value when requested by the system.
    • If Preference the provides its own UI (such as a dialog), save and restore the state to handle lifecycle changes (such as when The user rotates the screen).

The following sections describe how to accomplish each of the these tasks.

Specifying the user interface

If you are directly extend Preference the class, you need to implement to define the action that occurs when the onClick() user selects The item. However, most custom settings extend to DialogPreference show a dialog, which simplifies the procedure. When you extend DialogPreference , you must call setDialogLayoutResourcs() during in the class constructor to specify the layout for the dialog.

For example, here's the constructor for a custom this DialogPreference declares the layout and specifies the text for the default POS Itive and Negative dialog buttons:

 Public class extends dialogpreference {    public  numberpickerpreference (context context, AttributeSet Attrs) {         Super (context, attrs);                Setdialoglayoutresource (r.layout.numberpicker_dialog);        Setpositivebuttontext (Android. R.string.ok);        Setnegativebuttontext (Android. R.string.cancel);                Setdialogicon (null);    }    ...}
Saving the setting ' s value

You can save a value for the setting at any time by calling one Preference of the class ' s persist*() methods, such as persistInt() if the S Etting ' s value is an integer or to persistBoolean() save a Boolean.

Note:  Each Preference can save is only one data type, so you must use the persist*() method appropriate for the data type used by your custom Preference.

When you choose to persist the setting can depend on which Preference class you extend. If you extend DialogPreference and then you should persist the value is only when the dialog closes due to a positive result (the user Selec TS the "OK" button).

When a DialogPreference closes, the system calls the onDialogClosed() method. The method includes a Boolean argument that specifies whether the user result was "positive"-if the value true is and then th E user selected the positive button and you should save the new value. For example:

@Override protected void ondialogclosed (boolean  positiveresult) {    // when the user selects " OK ", persist the new value    if  (positiveresult) {        persistint (mnewvalue);    }}

In this example, was mNewValue a class member that holds the setting ' s current value. Calling persistInt() saves the value to the SharedPreferences file (automatically using the key, the specified in the XML file for this ).

Initializing the current value

When the system is adds your Preference to the screens, it calls to onSetInitialValue() notify you whether the setting have a persisted value. If There is no persisted value, this call provides you the default value.

onSetInitialValue()the method passes a Boolean, restorePersistedValue to indicate whether a value have already been persisted for the setting. If it true is and then your should retrieve the persisted value by calling one of the Preference class ' s getPersisted*() methods, such as for an integer value. You'll usually want to retrieve the persisted value so you can properly update the UI to reflect the previously saved Valu E.

If restorePersistedValue false is, then you should use the default value, which is passed in the second argument.

@Override protected void Onsetinitialvalue (boolean  restorepersistedvalue, Object defaultvalue) {    if  (restorepersistedvalue) {        //  Restore existingstate this         . Getpersistedint (default_value);     Else {        //  Set default state from the XML attribute        mcurrentvalue = (Integer) DefaultValue;        Persistint (Mcurrentvalue);    }}

Each getPersisted*() method takes a argument that specifies the default value to use in case there is actually no persisted value O R The key does not exist. In the example above, a local constant was used to specify the default value in case getPersistedInt() can ' t return a persisted value.

Caution:  You cannot use defaultValue getPersisted*() the as the default value in the method, because its value are always null when is restorePersistedValue true.

Providing a default value

If the instance of your Preference class specifies a default value ( android:defaultValue with the attribute) and then the system calls onGetDefaultValue() when It instantiates the object in order to retrieve the value. You must implement this method in order for the system to save the default value in the SharedPreferences . For example:

@Override protected int index) {    return  a.getinteger (index, default_value);}

The method arguments provide everything you need:the arrays android:defaultValue of attributes and the index position of the, which you mu St Retrieve. The reason must implement this method to extract the default value from the attribute are because you must specify a lo Cal default value for the attribute of the value is undefined.

Saving and restoring the Preference ' s state

Just like a View in a layout, your Preference subclass are responsible for saving and restoring the activity Or fragment is restarted (such as if the user rotates the screen). To properly save and restore the state of your Preference class, you must implement the lifecycle callback methods and onSaveInstanceState() .

The state of your was defined by a Preference object that implements the Parcelable interface. The Android framework provides such a object for you as a starting point to define your state object:the Preference.BaseSavedState class.

To define how your Preference class saves it state, you should extend the Preference.BaseSavedState class. You need to override just a few methods and define the CREATOR object.

For more apps, you can copy the following implementation and simply change the lines that handle the value if your Preference s Ubclass saves a data type other than an integer.

Private Static classSavedstateextendsBasesavedstate {//Member that holds the setting ' s value//Change this data type to match the type saved by your Preference    intvalue;  Publicsavedstate (parcelable superstate) {Super(superstate); }     Publicsavedstate (Parcel source) {Super(source); //Get The current preference ' s valueValue = Source.readint ();//Change this to read the appropriate data type} @Override Public voidWritetoparcel (Parcel dest,intflags) {        Super. Writetoparcel (dest, flags); //Write The preference ' s valueDest.writeint (value);//Change this to write the appropriate data type    }    //Standard Creator object using a instance of this class     Public Static FinalParcelable.creator<savedstate> Creator =NewParcelable.creator<savedstate>() {         Publicsavedstate Createfromparcel (Parcel in) {return Newsavedstate (in); }         PublicSavedstate[] NewArray (intsize) {            return NewSavedstate[size]; }    };}

Preference.BaseSavedStatewith the above implementation of added to your app (usually as a subclass of your Preference subclass), and then need to Implement the onSaveInstanceState() and onRestoreInstanceState() methods for your Preference subclass.

For example:

@Overrideprotectedparcelable onsaveinstancestate () {FinalParcelable superstate =Super. Onsaveinstancestate (); //Check Whether this Preference is persistent (continually saved)    if(Ispersistent ()) {//No need to save instance state since it ' s persistent,//Use superclass state        returnsuperstate; }    //Create instance of custom Basesavedstate    Finalsavedstate MyState =Newsavedstate (superstate); //Set the state's value with the class member-holds current//Setting ValueMystate.value =Mnewvalue; returnMyState;} @Overrideprotected voidonrestoreinstancestate (parcelable state) {//Check Whether we saved the state in Onsaveinstancestate    if(state = =NULL|| !state.getclass (). Equals (savedstate.class)) {        //didn ' t save the State and so call superclass        Super. Onrestoreinstancestate (state); return; }    //Cast state to custom basesavedstate and pass to superclasssavedstate MyState =(savedstate) state; Super. Onrestoreinstancestate (Mystate.getsuperstate ()); //Set This Preference ' s widgets to reflect the restored stateMnumberpicker.setvalue (Mystate.value);}

Android Preferences (7) custom preference, and Preferencedialog

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.