понедельник, 8 октября 2012 г.

Creating a Preference Activity in Android


In this tutorial we will build a preference screen using the PreferenceActivity class. Our main activity will contain 2 Buttons and a TextView. One of the buttons will open the preference screen, and the other will display the values stored in SharedPreferences.
The final output should look like this:

And here’s what happens when clicking on the Username/Password fields (left screenshot), and the List Preference field (right screenshot):

At a first glance it may look a bit intimidating, but as you will see later, actually it’s quite easy to define a preference screen. Trust me, I’m an engineer! (c) :)
To put all this things together in a fashionable way, we will be using the PreferenceActivity class. The good thing about this class is that the definition of layout file it’s very simple. It provides custom controls specially designed for preference screens. Another good thing is that you don’t need to write code to save the values from preference screen to SharedPreferences. All this work is done automatically by the activity.

So, lets begin creating our preference screen
1. Create a new project in Eclipse:
Project: PreferenceDemoTest
Activity: PreferenceDemoActivity
2. Create a new Android XML file prefs.xml in the folder res/xml/. This file will contain the layout for our preference screen:
01<?xml version="1.0" encoding="utf-8"?>
02<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
03 <PreferenceCategory
04   android:summary="Username and password information"
05   android:title="Login information" >
06  <EditTextPreference
07     android:key="username"
08     android:summary="Please enter your login username"
09     android:title="Username" />
10  <EditTextPreference
11     android:key="password"
12     android:summary="Enter your password"
13     android:title="Password" />
14 </PreferenceCategory>
15 
16 <PreferenceCategory
17   android:summary="Username and password information"
18   android:title="Settings" >
19  <CheckBoxPreference
20     android:key="checkBox"
21     android:summary="On/Off"
22     android:title="Keep me logged in" />
23 
24  <ListPreference
25     android:entries="@array/listOptions"
26     android:entryValues="@array/listValues"
27     android:key="listpref"
28     android:summary="List preference example"
29     android:title="List preference" />
30 </PreferenceCategory>
31</PreferenceScreen>
Notice that the root element of prefs.xml is the <PreferenceScreen> elementand not a RelativeLayout or LinearLayout for example. When a PreferenceActivity points to this layout file, the <PreferenceScreen> is used as the root, and the contained preferences are shown.
<PreferenceCategory> – defines a preference category. In our example the preference screen is split in two categories: “Login Information” and “Settings”
<EditTextPreference> – defines a text field for storing text information.
<CheckBoxPreference> – defines a checkbox.
<ListPreference> – defines a list of elements. The list appears as group of radio buttons.

3. At this stage the prefs.xml might complain that the @array/listOptions and @array/listValuesresources cannot be found.
To fix this create a new XML file array.xml in the folder res/values/. This file will contain the elements of the ListPreference.
01<?xml version="1.0" encoding="utf-8"?>
02 <resources>
03   <string-array name="listOptions">
04     <item>Option 1</item>
05     <item>Option 2</item>
06     <item>Option 3</item>
07     </string-array>
08 
09   <string-array name="listValues">
10     <item>1 is selected</item>
11     <item>2 is selected</item>
12     <item>3 is selected</item>
13   </string-array>
14 </resources>
The “listOptions” array defines the elements of the list, or with other words, the labels.
The “listValues” array defines the values of each element. These are the values that will be stored in the SharedPreferences. The number of list options and list values should match. The first list value is assinged to the first list option, the second value to the second option,… and so on.

4. Create a new class PrefsActivity.java that extends PreferenceActivity:
1public class PrefsActivity extends PreferenceActivity{
2 
3@Override
4protected void onCreate(Bundle savedInstanceState) {
5   super.onCreate(savedInstanceState);
6   addPreferencesFromResource(R.xml.prefs);
7}
8}
Notice that instead of the traditional setContentView(), we use hereaddPreferencesFromResource() method. This inflates our prefs.xml file and uses it as the Activity’s current layout.

5. Add the PrefsActivity.java to the AndroidManifest file:
1<application
2......./>
3  <activity
4    android:name=".PrefsActivity"
5    android:theme="@android:style/Theme.Black.NoTitleBar" >
6  </activity>
7</application>

6. Now, to test our preference activity lets modify the main.xml layout file by adding 2 Buttons and 1 TextView. One of the buttons will open the preference screen, and the other will display the values stored in SharedPreferences.
main.xml:
01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03  android:layout_width="fill_parent"
04  android:layout_height="fill_parent"
05  android:orientation="vertical" >
06 
07<Button
08  android:id="@+id/btnPrefs"
09  android:layout_width="wrap_content"
10  android:layout_height="wrap_content"
11  android:text="Preferences Screen" />
12 
13<Button
14  android:id="@+id/btnGetPreferences"
15  android:layout_width="wrap_content"
16  android:layout_height="wrap_content"
17  android:text="Display Shared Preferences" />
18 
19<TextView
20  android:id="@+id/txtPrefs"
21  android:layout_width="wrap_content"
22  android:layout_height="wrap_content" />
23 
24</LinearLayout>

7. Finally, modify the PreferenceDemoActivity to handle our logic implementation:
01public class PreferenceDemoActivity extends Activity {
02TextView textView;
03 
04@Override
05public void onCreate(Bundle savedInstanceState) {
06   super.onCreate(savedInstanceState);
07   setContentView(R.layout.main);
08 
09   Button btnPrefs = (Button) findViewById(R.id.btnPrefs);
10   Button btnGetPrefs = (Button) findViewById(R.id.btnGetPreferences);
11 
12   textView = (TextView) findViewById(R.id.txtPrefs);
13 
14   View.OnClickListener listener = new View.OnClickListener() {
15 
16   @Override
17   public void onClick(View v) {
18   switch (v.getId()) {
19   case R.id.btnPrefs:
20      Intent intent = new Intent(PreferenceDemoActivity.this,
21      PrefsActivity.class);
22      startActivity(intent);
23      break;
24 
25   case R.id.btnGetPreferences:
26      displaySharedPreferences();
27      break;
28 
29   default:
30     break;
31   }
32   }
33   };
34 
35   btnPrefs.setOnClickListener(listener);
36   btnGetPrefs.setOnClickListener(listener);
37}
38 
39private void displaySharedPreferences() {
40   SharedPreferences prefs = PreferenceManager
41    .getDefaultSharedPreferences(PreferenceDemoActivity.this);
42 
43   String username = prefs.getString("username""Default NickName");
44   String passw = prefs.getString("password""Default Password");
45   boolean checkBox = prefs.getBoolean("checkBox"false);
46   String listPrefs = prefs.getString("listpref""Default list prefs");
47 
48   StringBuilder builder = new StringBuilder();
49   builder.append("Username: " + username + "\n");
50   builder.append("Password: " + passw + "\n");
51   builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");
52   builder.append("List preference: " + listPrefs);
53 
54   textView.setText(builder.toString());
55}
56}
Here we attach 2 listeners for each button and display the values retrieved from  SharedPreferences in a TextView.
By this time you should compile and run successfully the application.

Отблагодарить можно через форму справа "Donate" ... )

To reward you via the form on the right "Donate" ... )

:)

Комментариев нет :

Отправить комментарий

друзья )

Сохраняйте и делитесь желаниями, и не забывайте о важных датах! парсинг центр