We can create ourselves preference activity in our android applications, but this is a tedious work, we have to operate every thing by ourself, e.g. rectrieve data from shared preference and set controls status, store data in shared preference and so on.
Thanks for android preferences framework, all the things become simple.Following three setps below, we can make a useful preference acitvity.
The activity looks like:
First, Defining a Preference Screen Layout in XML
An exmaple layout file as follows:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="PREF_AUTO_UPDATE"
android:title="Auto refresh"
android:summary="Select to turn on automatic updating"
android:defaultValue="true"
/>
<ListPreference
android:key="PREF_UPDATE_FREQ"
android:title="Refresh frequency"
android:summary="Frequency at which to refresh earthquake list"
android:entries="@array/update_freq_options"
android:entryValues="@array/update_freq_values"
android:dialogTitle="Refresh frequency"
android:defaultValue="60"
/>
<ListPreference
android:key="PREF_MIN_MAG"
android:title="Minimum magnitude"
android:summary="Select the minimum magnitude earthquake to report"
android:entries="@array/magnitude_options"
android:entryValues="@array/magnitude"
android:dialogTitle="Magnitude"
android:defaultValue="3"
/>
</PreferenceScreen>
Second,Create a class inherits from PreferenceActivity
This class is used to host preference hierarchy defined using the preferences xml file.
The code looks like:
public class Preferences extends PreferenceActivity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.userpreferences);
}
}
R.xml.userpreferences is the file we create in first setp.
Third, Add Shared Preferences Change Listener
The code snippet as follows:
public class MyActivity extends Activity implements
OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle SavedInstanceState) {
// Register this OnSharedPreferenceChangeListener
Context context = getApplicationContext();
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);
prefs.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// TODO Check the shared preference and key parameters and change UI or
// behavior as appropriate.
}
}