手动调用Callback方法初始化默认值是一种好习惯吗?

时间:2015-01-03 09:53:48

标签: java android listener android-preferences

我遇到了一个android 偏好活动(用于支持低于 3.0 的设备,而不是新的偏好片段

在下面的示例代码中,首次在摘要中显示当前选定的值,他们会调用onPreferenceChange(..),这是本例中的回调方法。

虽然我现在理解了整个过程但是我花了很长时间才弄明白发生了什么,因为我是android的新手,我从来没有在actionPerformed(...) <中调用ActionListener之类的听众。 em> class 等直接。

这是不好的做法吗? ,对此有什么好的选择?。

SettingsActivity.class

public class SettingsActivity extends PreferenceActivity
        implements Preference.OnPreferenceChangeListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
    addPreferencesFromResource(R.xml.pref);

// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));//used here similar to a view id
        //getString(R.String...) extracts the string value from strings.xml
    }
    /**
     * Attaches a listener so the summary is always updated with the preference value.
     * Also fires the listener once, to initialize the summary (so it shows up before the value
     * is changed.)
     */
    private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
        onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }
    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();
        if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
            ListPreference listPreference = (ListPreference) preference;
            int prefIndex = listPreference.findIndexOfValue(stringValue);
            if (prefIndex >= 0) {
                preference.setSummary(listPreference.getEntries()[prefIndex]);
            }
        } else {
// For other preferences, set the summary to the value's simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }
}

0 个答案:

没有答案