Android Learning Note (40): Preference use

Source: Internet
Author: User

Preference is literally a preference, translated as a preference.

Some configuration data, some of the content we last clicked on. We hope that the next time the app is tuned, it will still work, without the user having to configure or choose again. Android provides a way to preference this key-value pair to handle such situations and proactively save the data. and comes into effect at the same time, Android provides a similar layout way to do prefernce layouts.

A simple sample of preferenece

Step 1: Write preference XML, add our preference XML file under res/xml/, such as the name C21preference.xml

<?xml version= "1.0" encoding= "Utf-8"?>
<!--preference are organized in Preferencescreen and Preferencecategory. Preferencecategory are hierarchical organization relationships. The sample experience in the following example. And Preferencescreen is the most plain and basic way.
<Preferencescreen
xmlns:android= "Http://schemas.android.com/apk/res/android">
<!--has four basic builds. This sample learns two. Inside the content comparison chart, very easy to understand, Ringtonepreference is the choice of ring tone, here gives two options, the system default ring tone and silent--
<checkboxpreference android:key= "
checkbox"
Android:title= "
CheckBox Preference"
Android:summary= "
Check it on, check it off "/>
<ringtonepreference android:key= "
ringtone"
Android:title= "
Ringtone Preference"
android:showdefault= "
true"
Android:showsilent= "
true"
Android:summary= "
Pick a tone, any tone"/>
</PreferenceScreen>

Step 2: Call the XML in the Java source code. Generate the corresponding preference interface

public class Chapter21test1 extends preferenceactivity {
  
Span style= "Font-family:microsoft Yahei; Color: #c0c0c0 ">  @Override
    protected void OnCreate (Bundle savedinstancestate) {
       
super.oncreate (savedinstancestate);
         Addpreferencesfromresource (r.xml.c21preference);
    }
}

The same way as in layout. The code is very easy.

The biggest difference from the previous interface is that when we select the checkbox or select the ringtone, the selection result is retained, and when we exit actitvity, the last option remains. Once again, we applied to the simulator load and found that the previous option still exists. We can use preference. It is very convenient to save and read the data without manual.

Step 3: Get the Preference data

Data can be preserved in the preference interface, and we want to be able to read the data so that it can be used in other activity. Suppose there is another activity associated with these data, and you want to be able to synchronize in real time. The data reserved by preference is read in Onresume (), and then related updates are made.

The first thing to do is to get preferences, and then get the value from key by the way it gets. In XML, the checkbox key is "checkbox" and the value type is a Boolean value. The value of Rintong is string, for example:

protected void Onresume () {//In another activity
Super.onresume ();
Sharedpreferences prefs =preferencemanager.getdefaultsharedpreferences(this);
System.out.println (The new Boolean (prefs.getboolean("
checkbox", false)). ToString ());//false indicates that the return value of the checkbox key is not found.
System.out.println (prefs.getstring("
ringtone" ," <unset> "));//<unset> indicates that the return value of the key is not found Ringtong
}

Getting preferences can be done in three ways:
Getpreferences (): ability to acquire preference in the same activity;
Second, getsharedpreferences (): Ability to obtain the preferences () of the mapping level. In this example, because we are encapsulated in the same app. can also use sharepreferences prefs = getsharedpreferences ("Com.wei.android.learning_preferences", 0); The format of the first parameter name is < package_name>_preferences;
Third, getdefaultsharedpreferences (): Is our example of the way, through the Android Preferences manager to obtain its managed preferences.

Preferenece operation of data

In the example above. The value of the preference is preserved and can be read in other activity. Suppose you need to erase the data. The ability to clear the prefernece of a name through remove (). Clear () clears all the preferences.

We can get the editor of Preferences by using edit (), and then edit and change it. The change value is saved by commit ().

Preferenece XML

Preference XML can be organized by preferencecategory. Preferencecategory is able to combine several builds and add headings. We still use the preceding XML sample to organize through preferencecategory, such as the following: comparison with the previous sample. Organize Chekcbox and Rintong into a category and add the title of "Simple Preferences".

<?xml version= "1.0" encoding= "Utf-8"?

>
<preferencescreen
xmlns:android=" http://schemas.android.com/apk/res/android " >
       < preferencecategory android: Title = "Simple Preferences";
            <checkboxpreference android:key= "checkbox" ..../
            <ringtonepreference android:key= " Ringtone ".../>

       </ preferencecategory >
</preferencescreen>

Preferencecategory can also nest Preferencescreen. The content in the Preferencescreen will be displayed by a screen. We add a preferencecategory with nested preferencescreen behind the above example. The entire preferencescreen appears as a component. Click on a new screen, defined by the into Preferencescreen. Through this relationship, we are able to organize our own preference architecture.

<?xml version= "1.0" encoding= "Utf-8"?>
<preferencescreen
xmlns:android= "Http://schemas.android.com/apk/res/android">
<preferencecategory android:title= "Simple Preferences" >
<checkboxpreference android:key= "checkbox" ..../>
<ringtonepreference android:key= "Ringtone" .../>
</PreferenceCategory>

<preferencecategory android:title= "Detail Screens" >
<preferencescreen android:title= "Detail"
android:summary= "addtional preference Help in another page" >
<checkboxpreference
android:key= "CheckBox2"
Android:title= "another Checkbox"
Android:summary= "On or OFF, It ' s a problem ..."
/>
</preferencescreen>
</preferencecategory>
</PreferenceScreen>

In the previous example we used the checkbox and Ringtong, in the following example, we experimented with another two build edittext and list. Both of these are the way the frames are already framed.

In the above example we continue to add content

<?xml version= "1.0" encoding= "Utf-8"?>
<preferencescreen ...>
......     

<preferencecategory android:title= "Other Preferences" >
<edittextpreference android:key= "text"
Android:title= "
Text Entry Dialog"
Android:summary= "
Click to pop up a field for entry"
Android:dialogtitle= "
Enter Something useful"/>
<listpreference android:key= "list"
Android:title= "
Selection Dialog"
Android:summary= "
Click to pop yo a list for select"
android:entries= "@array/cities"
android:entryvalues= "@array/airport_codes"

Android:dialogtitle= "
Choose a city"/>
</PreferenceCategory>
</PreferenceScreen>

The list consists of two references @array/cities and @array/airport_codes. We define these two arrays in the resource file. The contents are as follows:
<resource>
<string-array>
<item>Pittsburgh</item>
<item>Allentown/Bethlehem</item>
<item>Erie</item>
... ...
</string-array>
<string-array name= "Airport_codes" >
<item>PHL</item>
<item>PIT</item>
<item>ABE</item>
... ...
</string-array>
</resources>

The execution results are as seen in the image on the right. For EditText, the value of the key-value pair is string. That is, what the user enters in the input box. The list is slightly more complicated, and there is a entires in setting the Listpreference property. This is what the list shows to the user, assuming we're going to get the value of the preference. In this sample is prefs.getstring ("list", "<unset>"), and the corresponding value in Entryvalues is returned. For example, if we select the first Item:pittsburgh, we get a value of PHL. Entries and Entryvalues are one by one corresponding.

RELATED Links: My Android development related articles

Android Learning Note (40): Preference use

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.