【问题标题】:How to create a Listener to Preferences changes in Preferences activity?如何在首选项活动中创建首选项更改的侦听器?
【发布时间】:2016-06-29 20:42:31
【问题描述】:

我的应用中有 Preferences 活动,它具有 ListPreference,因此用户可以选择应用的语言。

应用会在用户关闭 Preferences 活动后立即显示新语言。

我想为 ListPreference 创建一个侦听器,以便在触发侦听器时(就在用户从 ListPreference 中选择语言/选择项目之后)重新启动应用程序。

我该怎么做?

设置活动:

public class SettingsActivity extends AppCompatPreferenceActivity {
/**
 * A preference value change listener that updates the preference's summary
 * to reflect its new value.
 */
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
    @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.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);

            // Set the summary to reflect the new value.
            preference.setSummary(
                    index >= 0
                            ? listPreference.getEntries()[index]
                            : null);

        } else {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }
};


/**
 * Binds a preference's summary to its value. More specifically, when the
 * preference's value is changed, its summary (line of text below the
 * preference title) is updated to reflect the value. The summary is also
 * immediately updated upon calling this method. The exact display format is
 * dependent on the type of preference.
 *
 * @see #sBindPreferenceSummaryToValueListener
 */
private static void bindPreferenceSummaryToValue(Preference preference) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    // Trigger the listener immediately with the preference's
    // current value.
    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.getContext())
                    .getString(preference.getKey(), ""));
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();
    setTitle(R.string.action_settings);
}

/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
private void setupActionBar() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        // Show the Up button in the action bar.
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        if (!super.onMenuItemSelected(featureId, item)) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return true;
    }
    return super.onMenuItemSelected(featureId, item);
}

/**
 * This method stops fragment injection in malicious applications.
 * Make sure to deny any unknown fragments here.
 */
protected boolean isValidFragment(String fragmentName) {
    return PreferenceFragment.class.getName().equals(fragmentName)
            || GeneralPreferenceFragment.class.getName().equals(fragmentName);
}

/**
 * This fragment shows general preferences only. It is used when the
 * activity is showing a two-pane settings UI.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref_general);
        setHasOptionsMenu(true);

        // Bind the summaries of EditText/List/Dialog/Ringtone preferences
        // to their values. When their values change, their summaries are
        // updated to reflect the new value, per the Android Design
        // guidelines.
        bindPreferenceSummaryToValue(findPreference("example_text"));
        bindPreferenceSummaryToValue(findPreference(getString(R.string.language_shared_pref_key)));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            getActivity().finish();
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

}

pref_general.xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<ListPreference
    android:defaultValue="@string/language_code"
    android:entries="@array/pref_languages_list_titles"
    android:entryValues="@array/pref_languages_list_values"
    android:key="@string/language_shared_pref_key"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="@string/pref_title_language" />

</PreferenceScreen>

谢谢!!!

【问题讨论】:

  • 再次启动 mainActivity 并在它的 onCreate 方法中确保检查从 sharedPrefs 中选择的语言并相应地更改语言环境。
  • 已经这样做了。那不是我问的。我只想创建ListPreference的监听器
  • 那么你问了什么?你不知道如何启动 MainActivity 并销毁所有其他的?使用preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener)
  • 听起来你已经知道如何实现共享首选项更改监听器了;到底是什么让你绊倒了?
  • 如何创建 ListPreference 的监听器以及何时触发应用程序将重新启动。

标签: java android android-preferences preferenceactivity listpreference


【解决方案1】:

这是我在一个项目中设置的共享首选项 chaneg 侦听器的一些快速示例代码;它位于服务的 onCreate 中,但显然可以检测到我的共享首选项的更改源自我应用程序中的任何位置。

private SharedPreferences.OnSharedPreferenceChangeListener listener;


//Loads Shared preferences
prefs = PreferenceManager.getDefaultSharedPreferences(this);

//Setup a shared preference listener for hpwAddress and restart transport
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
           if (key.equals(/*key for shared pref you're listening for*/) {
               //Do stuff; restart activity in your case
            }
        };

prefs.registerOnSharedPreferenceChangeListener(listener);

【讨论】:

  • 我应该把它放在 onCreate 方法中吗?
  • 很高兴它对你有用。是的,您通常希望在主要活动的 onCreate 中使用它,以便在更改这些值之前设置侦听器。该行为与您希望的行为有何不同,我或许可以提供帮助?
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多