The previous example shows how to use preferenceactivity to display the modified application preferences, and the user's modifications to the preferences are automatically stored in the corresponding shared preferences of the application.
This example shows how to get the preference value from an activity by preferenceactivity. For example, in the actual application through the Preferenceactivity interface to obtain user preferences or configuration.
Because you want to return a value from preferenceactivity, use Startactivityforresult to start a derived class of preferenceactivity.
Advancedpreferences is a derived class for preferenceactivity, which defines two preferences items for r.xml.advanced_preferences. One is a custom preference (described later in mypreference) whose value type is an integer and the other is Checkboxpreference, whose UI is as follows:
The purpose of this example is to obtain the value of mypreference by setting the advancedpreferences, mypreference is defined in R.xml.advanced_preferences 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= "/>"
We can see that its key is defined as my_preference.
Call the Advancedpreferences code as follows:
// When the button is clicked, launch a activity through this intent New Intent (). SetClass (This, advancedpreferences. Class); // Make it a subactivity so we know when it returns Startactivityforresult (Launchpreferencesintent, request_code_preferences);
Handling Advancedpreferences Returns:
@Overrideprotected voidOnactivityresult (intRequestcode,intResultCode, Intent data) { Super. Onactivityresult (Requestcode, ResultCode, data); //The preferences returned if the request code is what we had given//earlier in Startsubactivity if(Requestcode = =request_code_preferences) { //Read A sample value they has setUpdatecountertext (); } } Private voidUpdatecountertext () {//Since we ' re in the same package, we can use this context to get//The default shared preferencesSharedpreferences sharedpref = preferencemanager.getdefaultsharedpreferences ( This); Final intCounter = Sharedpref.getint (advancedpreferences.key_my_preference, 0); Mcountertext.settext (getString (r.string.counter_value_is)+ " " +counter); }
You can see that the value of a preference obtained from a shared preferences is defined by its key value and then called GetXXX (key:). To obtain.
The value of Mypreference is displayed in Launchingpreferences after returning from Advancedpreferences.
"Sail Plan 028" 2015 Sail plan Android Apidemo Devil Step app->preferences->launching Preferences Other activity get value in preference