Understanding Edit TextPreference

The preferences framework also provides a free-form text preference called EditTextPreference. This preference allows you to capture raw text rather than ask the user to make a selection. To demonstrate this, let's assume you have an application that generates Java code for the user. One of the preference settings of this application might be the default package name to use for the generated classes. So here, you want to display a text field to the user and allow her to set the package name for the generated classes. Figure 11-4 shows the UI and Listing 11-5 shows the XML.

Set Package Name

Set the package name for generated code

Set Package Name

Set the package name for generated code

Package I

com.and.roid|

Figure 11-4. Using the EditTextPreference

Listing 11-5. An Example of an EditTextPreference // packagepref.xml

<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="package_name_screen" android:title="Package Name" android:summary="Set package name">

<EditTextPreference android:key="package_name_preference" android:title="Set Package Name"

android:summary="Set the package name for generated code" android:dialogTitle="Package Name" />

</PreferenceScreen>

// EditTextPreferenceActivity.java import android.os.Bundle;

import android.preference.PreferenceActivity;

public class EditTextPreferenceActivity extends PreferenceActivity{

^Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.packagepref);

You can see that Listing 11-5 defines a PreferenceScreen with a single EditTextPreference as a child. The generated UI for the listing features the PreferenceScreen on the left and the EditTextPreference on the right (see Figure 11-4). When the user selects "Set Package Name," she is presented with a dialog to input the package name. When she clicks the OK button, the preference is saved to the preference store.

As with the other preferences, you can obtain the EditTextPreference from your activity class by using the preference's key. Once you have the EditTextPreference, you can manipulate the actual EditText by calling getEditText() —if, for example, you want to apply validation, preprocessing, or postprocessing on the value that the user types in the text field.

Now let's look at the preferences framework's RingtonePreference.

0 0

Post a comment