RingtonePreference not firing OnPreferenceChangeLi

2019-02-22 18:36发布

Every other preference I have fires its OnPreferenceChangeListener. However, my RingtonePreference it doesn't:

p = getPreferenceScreen().findPreference("pref_tone");
String rname = preferences.getString("pref_tone",Settings.System.DEFAULT_RINGTONE_URI.toString());
String name = ringtoneToName(rname);
p.setSummary(name);
p.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
    // Never hits here!
    String v = (String) newValue;
    preference.setSummary(ringtoneToName(v));           
    return true;
}
});

3条回答
看我几分像从前
2楼-- · 2019-02-22 18:48

Note that a RingtonePreference uses an Activity for the ringtone picker.

If you are using a RingtonePreference in a support PreferenceFragment (android.support.v4.preference.PreferenceFragment) then the RingtonePreference ends up erroneously using the parent Activity instead of the PreferenceFragment when calling startActivityForResult. This means that the onActivityResult callback gets called on the parent Activity as well. The easiest workaround to fix this problem is to override onActivityResult in the parent Activity and make sure it forwards the callback to the PreferenceFragment. For example like this:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Fragment f = getSupportFragmentManager().findFragmentByTag(PREFERENCE_FRAGMENT_TAG);
    if (f != null) {
        f.onActivityResult(requestCode, resultCode, data);
    }
}
查看更多
家丑人穷心不美
3楼-- · 2019-02-22 19:06

Those who are still facing problem, if you are using preference fragment then add the following code inside the preference fragment`

findPreference(getString(R.string.notification_key)).setOnPreferenceChangeListener(this);

@Override
public boolean onPreferenceChange(Preference preference, Object newVal) {

    if (preference.getKey().equals(getString(R.string.notification_key))) {

        Ringtone ringtone = RingtoneManager.getRingtone(getActivity(), Uri.parse(newVal.toString()));
        String name = ringtone.getTitle(getActivity());
        preference.setSummary(name);
    }

    return false;
}

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode,resultCode,data);
    }

After this your onPreferenceChange method should get called

查看更多
姐就是有狂的资本
4楼-- · 2019-02-22 19:12

onActivityResult had to call super.onActivityResult is the fix

查看更多
登录 后发表回答