Java Code Examples for android.support.v7.preference.Preference#setOnPreferenceChangeListener()

The following examples show how to use android.support.v7.preference.Preference#setOnPreferenceChangeListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FragmentSettings.java    From fingen with Apache License 2.0 6 votes vote down vote up
/**
 * 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 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.
    if (preference instanceof MultiSelectListPreference) {

        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, convertValuesToSummary((MultiSelectListPreference) preference));
    } else {
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }
}
 
Example 2
Source File: SettingsFragment.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreatePreferences(Bundle bundle, String s) {

    // Add visualizer preferences, defined in the XML file in res->xml->pref_visualizer
    addPreferencesFromResource(R.xml.pref_visualizer);

    SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
    PreferenceScreen prefScreen = getPreferenceScreen();
    int count = prefScreen.getPreferenceCount();

    // Go through all of the preferences, and set up their preference summary.
    for (int i = 0; i < count; i++) {
        Preference p = prefScreen.getPreference(i);
        // You don't need to set up preference summaries for checkbox preferences because
        // they are already set up in xml using summaryOff and summary On
        if (!(p instanceof CheckBoxPreference)) {
            String value = sharedPreferences.getString(p.getKey(), "");
            setPreferenceSummary(p, value);
        }
    }
    // COMPLETED (3) Add the OnPreferenceChangeListener specifically to the EditTextPreference
    Preference preference = findPreference(getString(R.string.pref_size_key));
    preference.setOnPreferenceChangeListener(this);
}
 
Example 3
Source File: SettingsFragment.java    From IslamicLibraryAndroid with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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(@NonNull Preference preference) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    // Trigger the listener immediately with the preference's
    // current value.
    final String key = preference.getKey();
    if (preference instanceof MultiSelectListPreference) {
        Set<String> summary = SharedPreferencesCompat.getStringSet(
                PreferenceManager.getDefaultSharedPreferences(preference.getContext()),
                key,
                new HashSet<>());
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, summary);
    } else if (preference instanceof ColorPreference) {
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, ((ColorPreference) preference).getColor());
    } else if (preference instanceof SeekBarPreference) {
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, ((SeekBarPreference) preference).getValue());
    } else {
        String value = PreferenceManager
                .getDefaultSharedPreferences(preference.getContext())
                .getString(key, "");
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, value);
    }
}
 
Example 4
Source File: PreferencesFragmentSummary.java    From AndroidBlueprints with Apache License 2.0 6 votes vote down vote up
/**
 * Init single Preference
 */
protected void initPrefsSummary(SharedPreferences sharedPreferences,
                                Preference p) {
    if (p instanceof PreferenceCategory) {
        PreferenceCategory pCat = (PreferenceCategory) p;
        int pcCatCount = pCat.getPreferenceCount();
        for (int i = 0; i < pcCatCount; i++) {
            initPrefsSummary(sharedPreferences, pCat.getPreference(i));
        }
    } else {
        updatePrefsSummary(sharedPreferences, p);
        if (p instanceof RingtonePreference) {
            p.setOnPreferenceChangeListener(new RingToneOnPreferenceChangeListener());
            mRingtonePreference = (RingtonePreference) p;
        }
    }
}
 
Example 5
Source File: AccountSettingsActivity.java    From android_packages_apps_GmsCore with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreatePreferencesFix(@Nullable Bundle savedInstanceState, String rootKey) {
    super.onCreatePreferencesFix(savedInstanceState, rootKey);
    Preference pref = findPreference(PREF_AUTH_VISIBLE);
    if (pref != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            pref.setVisible(false);
        } else {
            pref.setOnPreferenceChangeListener((preference, newValue) -> {
                if (newValue instanceof Boolean) {
                    AccountManager am = AccountManager.get(getContext());
                    for (Account account : am.getAccountsByType(AuthConstants.DEFAULT_ACCOUNT_TYPE)) {
                        am.setAccountVisibility(account, PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, (Boolean) newValue ? VISIBILITY_USER_MANAGED_VISIBLE : VISIBILITY_USER_MANAGED_NOT_VISIBLE);
                    }
                }
                return true;
            });
        }
    }
}
 
Example 6
Source File: SettingsFragment.java    From sleep-cycle-alarm with GNU General Public License v3.0 5 votes vote down vote up
private void bindPreferenceToListener(Preference preference) {
    preference.setOnPreferenceChangeListener(preferenceChangeListener);
    preferenceChangeListener.onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.getContext())
                    .getString(preference.getKey(), ""));
}
 
Example 7
Source File: SettingsActivity.java    From home-assistant-Android with GNU General Public License v3.0 5 votes vote down vote up
private void updatePreferenceSummaries() {
    Preference enableLocationTracking = findPreference(Common.PREF_ENABLE_LOCATION_TRACKING);
    enableLocationTracking.setOnPreferenceChangeListener((preference, newValue) -> {
        if (newValue == Boolean.TRUE && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
            return false;
        }
        updateLocationTracker();
        return true;
    });

    Preference deviceName = findPreference(Common.PREF_LOCATION_DEVICE_NAME);
    deviceName.setSummary(getResources().getString(R.string.preference_location_device_name_summary, prefs.getString(deviceName.getKey(), "nothing")));
    deviceName.setOnPreferenceChangeListener((preference, newValue) -> {
        preference.setSummary(getResources().getString(R.string.preference_location_device_name_summary, newValue));
        updateLocationTracker();
        return true;
    });

    Preference updateInterval = findPreference(Common.PREF_LOCATION_UPDATE_INTERVAL);
    int selectedIndex = Arrays.binarySearch(getResources().getIntArray(R.array.location_update_interval_values), prefs.getInt(updateInterval.getKey(), 10));
    updateInterval.setSummary(getResources().getStringArray(R.array.location_update_interval_summaries)[selectedIndex]);

    Preference resetIgnoredSSLMismatches = findPreference(Common.PREF_RESET_HOST_MISMATCHES);
    if (prefs.getStringSet(Common.PREF_ALLOWED_HOST_MISMATCHES_KEY, null) == null) {
        resetIgnoredSSLMismatches.setSummary(R.string.preference_reset_host_mismatches_summary_empty);
        resetIgnoredSSLMismatches.setEnabled(false);
    }
}
 
Example 8
Source File: SettingsFragment.java    From octoandroid with GNU General Public License v3.0 5 votes vote down vote up
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(), ""));
    }
 
Example 9
Source File: PrinterDetailsFragment.java    From octoandroid with GNU General Public License v3.0 5 votes vote down vote up
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(), ""));
}
 
Example 10
Source File: SettingsFragment.java    From HideMockLocation with MIT License 5 votes vote down vote up
@Override
public void onCreatePreferencesFix(Bundle bundle, String s) {
    addPreferencesFromResource(R.xml.preferences);

    Preference showIconPref = findPreference(Common.PREF_SHOW_ICON);
    showIconPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            changeIconView((Boolean) newValue);
            return true;
        }
    });
}
 
Example 11
Source File: PrefsFragment.java    From AlarmOn with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.app_settings);

    getActivity().setTitle(R.string.app_settings);

    Preference.OnPreferenceChangeListener refreshListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            // Clear the lock screen text if the user disables the feature.
            if (preference.getKey().equals(AppSettings.LOCK_SCREEN)) {
                clearLockScreenText(getActivity());

                final String custom_lock_screen = getResources().getStringArray(R.array.lock_screen_values)[4];
                if (newValue.equals(custom_lock_screen)) {
                    DialogFragment dialog = new ActivityDialogFragment().newInstance(
                            CUSTOM_LOCK_SCREEN);
                    dialog.show(getFragmentManager(), "ActivityDialogFragment");
                }
            }

            final Intent causeRefresh = new Intent(getActivity(), AlarmClockService.class);
            causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH);
            getActivity().startService(causeRefresh);
            return true;
        }
    };

    // Refresh the notification icon when the user changes these preferences.
    final Preference notification_icon = findPreference(AppSettings.NOTIFICATION_ICON);
    notification_icon.setOnPreferenceChangeListener(refreshListener);
    final Preference lock_screen = findPreference(AppSettings.LOCK_SCREEN);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getPreferenceScreen().removePreference(lock_screen);
    } else {
        lock_screen.setOnPreferenceChangeListener(refreshListener);
    }

    final Preference appTheme = findPreference(AppSettings.APP_THEME_KEY);

    appTheme.setOnPreferenceChangeListener(this);

    if (!BuildConfig.DEBUG) {
        getPreferenceScreen().removePreference(
                findPreference(AppSettings.DEBUG_MODE));
    }

    findPreference(AppSettings.NOTIFICATION_TEXT).
            setOnPreferenceChangeListener(this);

    findPreference(getString(R.string.settings_about_key)).
            setOnPreferenceClickListener(this);
}
 
Example 12
Source File: UTilitiesPreferenceFragment.java    From utexas-utilities with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    Bundle args = getArguments();
    preferenceScreenKey = args.getString("preferenceScreenKey");
    super.onCreate(savedInstanceState);
    FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics.getInstance(getActivity());

    switch (preferenceScreenKey) {
        case "root":
            autologin = (CheckBoxPreference) findPreference("autologin");
            loginfield = findPreference("eid");
            passwordfield = findPreference("password");


            // bypass the default SharedPreferences and save the password to the
            // encrypted SP instead
            passwordfield.setOnPreferenceChangeListener((preference, newValue) -> {
                UTilitiesApplication.getInstance(getActivity()).getSecurePreferences().edit()
                        .putString(preference.getKey(), (String) newValue).apply();
                return false;
            });

            final Preference logincheckbox = findPreference(getString(R.string.pref_logintype_key));

            // Disable autologin when user switches to temp login
            logincheckbox.setOnPreferenceChangeListener((preference, newValue) -> {
                if (!((Boolean) newValue)) {
                    autologin.setChecked(false);
                }
                return true;
            });

            logincheckbox.setOnPreferenceClickListener(preference -> {
                UTilitiesApplication mApp = (UTilitiesApplication) getActivity().getApplication();
                boolean checked = ((CheckBoxPreference) preference).isChecked();
                if (checked) {
                    new AutoLoginWarningDialog().show(getChildFragmentManager(),
                            AutoLoginWarningDialog.class.getSimpleName());
                } else {
                    /*
                     * if they switch to temp login we'll save their EID, but
                     * clear their password for security purposes
                     */
                    mApp.getSecurePreferences().edit().remove("password").apply();
                    ba.notifyDataSetChanged();
                }
                // whenever they switch between temp and persistent, log them out
                mApp.logoutAll();
                setupLoginFields();
                firebaseAnalytics.setUserProperty("persistent_login", Boolean.toString(checked));
                return true;
            });

            setupLoginFields();

            final CheckBoxPreference analytics =
                    (CheckBoxPreference) findPreference(getString(R.string.pref_analytics_key));
            analytics.setOnPreferenceChangeListener((preference, newValue) -> {
                firebaseAnalytics.setAnalyticsCollectionEnabled((Boolean) newValue);
                return true;
            });

            final Preference about = findPreference("about");
            about.setOnPreferenceClickListener(preference -> {
                final Intent about_intent = new Intent(getActivity(), AboutMeActivity.class);
                startActivity(about_intent);
                return true;
            });
            break;
        case "experimental":
            final Preference updateBusStops = findPreference("update_stops");
            updateBusStops.setOnPreferenceClickListener(preference -> {
                try {
                    Utility.updateBusStops(getActivity());
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "Stops could not be written to file.",
                            Toast.LENGTH_SHORT).show();
                }
                return true;
            });
            break;
        default:
            throw new IllegalStateException("Unimplemented PreferenceScreen: " + preferenceScreenKey);
    }
}