Monthly Archives: September 2011

Android Preferences and Custom Buttons

I delved into the Preference API for Android this weekend. It turns out that I needed a couple of “buttons” to allow the user to go to the main screen (for various genuine reasons!). The Android API doesn’t let you do it with buttons, but there’s an equally easy way.

I have found that using a combination of a “placeholder” Preference and then providing an onClickListener in the corresponding PreferenceActivity class provides what I needed.

In my instance, I needed a “Save” and “Clear” option in my preference screen, so I added the following PreferenceCatgory in my preferences.xml

<PreferenceCategory
android:title="Manage Your Preferences">
<Preference
android:title="Save"
android:summary="Store your preferences"
android:key="savePref" />
<Preference
android:title="Clear"
android:summary="Clear all your preferences"
android:key="clearPref" />
</PreferenceCategory>

and then inside my onCreate method, I just assigned listeners to the individual clear and save preferences:

findPreference("clearPref").setOnPreferenceClickListener(onPreferenceClickListener);

which is given an instance of my inner `Preference.OnPreferenceClickListener` class:

private class PreferenceOnClickListener implements Preference.OnPreferenceClickListener {
public boolean onPreferenceClick(Preference preference) {
//Do something...
return false;
}
}

easy?!