9

似乎我无法找出PreferenceFragment::onPreferenceTreeClick(...)的返回值是如何解释的。在文档中没有提到如何使用返回值(Eclipse 说“@inheritDoc”并且Android HTML 引用有一个空的正文)。

我尝试在PreferenceActivity::onPreferenceTreeClick(...)上已弃用的 API 中查找它,但它所说的只是,它已被弃用。

此外,我尝试从该方法返回 true 和 false,但在我看来,它对任何东西都没有影响。

所以 - 如果有人可以请告诉我返回值发生了什么变化?

4

1 回答 1

17

The code that calls this is in Preference#performClick(PreferenceScreen preferenceScreen) and it does the following:

PreferenceManager preferenceManager = getPreferenceManager();
if (preferenceManager != null) {
    PreferenceManager.OnPreferenceTreeClickListener listener = preferenceManager
            .getOnPreferenceTreeClickListener();
    if (preferenceScreen != null && listener != null
            && listener.onPreferenceTreeClick(preferenceScreen, this)) {
        return;
    }
}

if (mIntent != null) {
    Context context = getContext();
    context.startActivity(mIntent);
}

returning true will return immediately while returning false will check if there is an Intent set for this PreferenceScreen and start the specified Activity.

If you return super.onPreferenceTreeClick(preferenceScreen, preference) you will also cause the following piece of code from PreferenceFragment to run

if (preference.getFragment() != null &&
        getActivity() instanceof OnPreferenceStartFragmentCallback) {
    return ((OnPreferenceStartFragmentCallback)getActivity()).onPreferenceStartFragment(
            this, preference);
}
return false;

This one checks if there is a Fragment to be shown. If not Preference will then look for an Intent.

TLDR

Preferences can start either Intents or Fragments. The meaning of the return value is

  • true : nothing happens, both fragments and intents are ignored
  • false : fragments are ignored, intents are executed
  • super.onPreference.. : tries fragment first, intent second

return false; or return super.onPreferenceTreeClick(...) should be usually the right thing to return. The meaning of the return value is roughly "Start Activity by intent if exist?". You should return true if you have specified an intent but don't want to start the activity. It does not matter in most other cases since you rarely handle clicks if you have that intent specified.

于 2013-08-21T16:50:56.033 回答