Android Learning Note (40): Use of preference

Source: Internet
Author: User

Preference translation as a preference, Bo friends suggest translating as the preferred item. Some configuration data, some of the things we clicked on last time, we wanted to be effective the next time the app was tuned, without the user having to configure or choose again. Android provides a way to handle this by preference this key-value pair, automatically saving the data, and immediately taking effect, while Android provides a similar layout for prefernce layouts.

A simple example 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 is organized in a way that has preferencescreen and preferencecategory,preferencecategory are hierarchical organization relationships, in the following example experience, And Preferencescreen is the most plain and basic way.
<PreferencescreenXmlns:android= "Http://schemas.android.com/apk/res/android" >
<!--has four basic builds, this example learns two. Inside the content of the comparison chart, it is easy to understand, Ringtonepreference is to choose the ring tone, here gives two options, the system default ring tone and silent--
<checkboxpreferenceAndroid:Key= "checkbox"
android:title= "CheckBox Preference"
android:summary= "Check it on, check it off"/>
<ringtonepreferenceAndroid: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 to generate the appropriate preference interface

public class Chapter21test1 extendspreferenceactivity{
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Addpreferencesfromresource (r.xml.c21preference);
}
}

As with layout, the code is simple. 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, and we re-apply it to the simulator load, The previous option was found to still exist. We can use preference instead of manually saving and reading the data, it is very convenient.

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. If another activity is associated with the data, and you want to be able to synchronize in real time, read the preference reserved data in Onresume (), and then make the related updates.

First to get preferences, and then through the key-value pair to get the value based on key, the checkbox in the XML key is "checkbox", the value of the type is a Boolean value, and the value of Rintong is string, for example:

    protected void Onresume () { //In another activity
         super.onresume ();
        sharedpreferences prefs = Preferencemanager.getdefaultsharedpreferences (this);
        system.out.println (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 this key is not found for Ringtong
    }

There are three ways to get preferences:
First, Getpreferences (): Can obtain the same activity in the preference;
Second, getsharedpreferences (): Can get the mapping level of Preferences (), in this case because we are encapsulated in the same app, you can also use sharepreferences prefs = Getsharedpreferences ("Com.wei.android.learning_preferences", 0); The format of the first parameter name is <package_name>_preferences ;
Getdefaultsharedpreferences (): This is the way we use the Android preference Manager to get the preferences it manages.

Preferenece operation of data

In the example above, the value of preference is preserved and can be read in other activity. If you need to clear the data, you can clear all the preferences by removing () clearing a name of Prefernece,clear (). We can get the editor of Preferences by using edit (), and then edit, modify, and save the modified value by commit ().

Preferenece XML

Preference XML can be organized by preferencecategory. Preferencecategory can combine several builds together and add headings. We still use the previous XML example, through Preferencecategory to organize, as follows: Compared with the previous example, the Chekcbox and Rintong organized into a category, and added the "Simple Preferences" title.

<?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 content in Preferencescreen,preferencescreen, which is displayed on another screen, We add a preferencecategory with nested preferencescreen behind the above example. The entire preferencescreen as a component appears, after clicking on a new screen, defined by the into Preferencescreen. Through this relationship, we can 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>
<preferencecategoryandroid:title= "Detail Screens" >
<PreferencescreenAndroid: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 the Ringtong, in the following example, we experimented with another two build edittext and list, both of which are the way to frame. In the example above we continue to add content

<?xml version= "1.0" encoding= "Utf-8"?>
<preferencescreen ...>
......
<preferencecategory android:title= "Other Preferences" >
<edittextpreferenceandroid:key= "Text"
android:title= "Text Entry Dialog"
android:summary= "Click to pop up a field for entry"
Android:dialogtitle= "Enter something Useful"/>
<listpreferenceandroid: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>

In list by two references @array/cities and @array/airport_codes, we define the 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 result of the operation is shown in the image on the right. For EditText, the value of the key-value pair is a string, which is what the user enters in the input box. The list is slightly more complicated, and in setting the Listpreference property there is a entires, which is displayed to the user in the list, and if we go to get preference value, in this example prefs.getstring ("list" , "<unset>"), returns the value corresponding to the entryvalues, for example, if we select the first Item:pittsburgh, we get the PHL. Entries and Entryvalues are one by one corresponding.

RELATED Links: My Android development related articles

More 5
    • Previous programming Methodology-Open Class study notes (vii)
    • The next article in Beijing
Top
the
Step

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.