Yashima
Yashima

Reputation: 2238

Refresh EditText of a Preference depending on the change of another Preference

I want to change the values displayed in each Preference in my PreferenceActivity based on the change in another preference.

I have an app that stores metric (float) values in Preferences. I also have a Preference called metric where the user can switch between usage of metric or imperial units.

I only store metric values, but when the user switches to imperial the app displays the imperial values.

Everything works fine if the user only switches the metric preference and leaves the PreferenceActivity. When he goes back the values are displayed the correct way. If he goes to look at userHeight for example the display still shows the metric value though.

In my PreferenceActivity I want to refresh the displayed values when the metric Preference changes (I am making sure that when these values should be stored they will be converted back correctly):

this.metric.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        final Boolean metric = Boolean.parseBoolean(newValue.toString());
        changeSummaries(metric);
        refreshDisplay(metric); 
        return true;
    }
});

What do I have to implement in the refreshDisplay(...) method? It would also help to know at what point of the lifecycle of the PreferenceActivity are the changed values committed?

Upvotes: 3

Views: 1372

Answers (1)

Yashima
Yashima

Reputation: 2238

I found it. At least for my specific problem I found a simple solution.

I had already extended EditTextPreference to be able to store something other than String

Before opening the dialog the onBindDialogView method is called at that point the other changed Preference is committed (I thought at first it might not be - a quick test proved me wrong). Simply overriding onBindDialogView allows me to change the displayed value to the one I want to display:

@Override
protected void onBindDialogView(View view) {
    super.onBindDialogView(view);
    getEditText().setText(getPersistedString(""));
}

@Override
protected String getPersistedString(String defaultReturnValue) {
    final Float storedValue = getPersistedFloat(-1);
    Float returnValue;
    if (MyPreferences.isMetric(getContext())) {
        returnValue = storedValue;
    } else {
        returnValue = this.unit.convertToImperial(storedValue);
    }
    return String.valueOf(returnValue);
}

Upvotes: 2

Related Questions