mtorres
mtorres

Reputation: 197

Programmatically change header summary

I have a preference_headers.xml file that I use to populate the headers for my settings. I would like to change the summary of the header to reflect the sharedPreference it holds. I have used an OnSharedPreferenceChangeListener for my other fragments and it works fine, but those are fragments under a preference screen, so I can access them like this..

SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
        EditTextPreference editTextPref = (EditTextPreference) findPreference("pref_text");
        editTextPref
                .setSummary(sp.getString("pref_text", "Set an email address"));

However, I want to edit the summary in the preference_headers file which is an intent to another activity, so I am not using a preference screen to store the shared preference.

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android" >

<header
    android:key="snooze_pref"
    android:summary="Default snooze is 10 minutes"
    android:title="Snooze Timer" >
    <intent
        android:action="android.intent.action.VIEW"
        android:targetClass="com.example.alarmvoltageservicev2.SnoozePicker"
        android:targetPackage="com.example.alarmvoltageservicev2" />
</header>

So my question is, how can I change the header summary above programmatically?

Upvotes: 1

Views: 655

Answers (2)

Jonathan Okie
Jonathan Okie

Reputation: 101

Assuming you are extending class PreferenceActivity, in your override of the onBuildHeaders method, after calling LoadHeadersFromResource, simply iterate through the "target" list that is passed to onBuildHeaders.

The list is of type Header which provides access to the summary text, as well as other settings.

(Sorry, I would provide a code example, but I write in C#-monodroid).

Upvotes: 1

Maurizio
Maurizio

Reputation: 4169

You can modify the summary programmatically when you set your ListAdapter by iterating through the Headers:

@Override
public void setListAdapter(ListAdapter adapter)
{
    int i, count;

    if (preferenceHeaders == null)
    {
        preferenceHeaders = new ArrayList<Header>();

        count = adapter.getCount();
        for (i = 0; i < count; ++i)
        {
            Header h = (Header) adapter.getItem(i);

            if(h.id == R.id.SOME_HEADER_ID_FROM_XML)
            {
                h.summary = "<new summary at runtime>";
            }
        }
    }

    super.setListAdapter(new PreferencesHeaderAdapter(this, preferenceHeaders));
}

Upvotes: 0

Related Questions