Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to mix a 'preference' and a preference header?

Tags:

android

I am developing a list of preferences for my app. Right now, there is only one, but I am sure there will be more as it gets fleshed out. My first preference is a 'theme' selector, where you choose the background color theme for some predefined elements.

I want a dual-pane interface for my upcoming prefs, but I don't need this preference in a 'subcategeory' that preference headers use. Is there a way to add a 'preference' (via XML) to the headers list so it will appear in the root preferences? I've looked... haven't seen any examples on if this is possible. Right now all I have is a button for 'Themes', which goes to a new preferences page (another fragment it lives under) which is making 2 clicks instead of one for a preference that doesn't go under a category.

like image 816
Mgamerz Avatar asked Feb 25 '14 02:02

Mgamerz


1 Answers

You can can make a preference header behave like a preference, though you can't actually put a Preference object into the list of preference headers. All you have to do is assign an ID to the header and override onHeaderClick() in your PreferenceActivity.

Here's an example of how to simulate a ListPreference as a preference header.

pref_headers.xml:

<preference-headers
    xmlns:android="http://schemas.android.com/apk/res/android">
    <header
        android:id="@+id/choose_theme" 
        android:title="Theme" />
</preference-headers>

MyPreferenceActivity.java:

public class MyPreferenceActivity extends PreferenceActivity {

    private CharSequence[] mThemeOptions =
            new CharSequence[] {"Red", "Blue", "Awesome"};
    private int mSelectedTheme = 0;

    @Override
    public void onBuildHeaders(List<Header> headers) {
        loadHeadersFromResource(R.xml.pref_headers, headers);
        for (Header h : headers) {
            if (h.id == R.id.choose_theme) {
                h.summary = mThemeOptions[mSelectedTheme];
            }
        }
    }

    @Override
    public void onHeaderClick(Header header, int position) {
        if (header.id == R.id.choose_theme) {
            OnClickListener l = new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    mSelectedTheme = which;
                    dialog.dismiss();
                    // Trigger the summary text to be updated.
                    invalidateHeaders();
                }
            };
            new AlertDialog.Builder(this)
                    .setSingleChoiceItems(mThemeOptions, mSelectedTheme, l)
                    .show();
            return;
        }
        super.onHeaderClick(header, position);
    }
}
like image 69
Newtonx Avatar answered Oct 23 '22 05:10

Newtonx