Java Code Examples for androidx.preference.Preference#setOnPreferenceClickListener()

The following examples show how to use androidx.preference.Preference#setOnPreferenceClickListener() . 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: PreferenceOnCheckOnSubscribe.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Override public void call(Subscriber<? super Boolean> subscriber) {
  verifyMainThread();

  Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
    @Override public boolean onPreferenceClick(Preference preference) {
      if (!subscriber.isUnsubscribed()) {
        subscriber.onNext(((CheckBoxPreference) preference).isChecked());
        return true;
      }
      return true;
    }
  };

  subscriber.add(new MainThreadSubscription() {
    @Override protected void onUnsubscribe() {
      preference.setOnPreferenceClickListener(null);
    }
  });

  preference.setOnPreferenceClickListener(listener);
}
 
Example 2
Source File: PreferenceClickOnSubscribe.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Override public void call(Subscriber<? super Preference> subscriber) {
  verifyMainThread();

  Preference.OnPreferenceClickListener listener = new Preference.OnPreferenceClickListener() {
    @Override public boolean onPreferenceClick(Preference preference) {
      if (!subscriber.isUnsubscribed()) {
        subscriber.onNext(preference);
        return true;
      }
      return true;
    }
  };

  subscriber.add(new MainThreadSubscription() {
    @Override protected void onUnsubscribe() {
      preference.setOnPreferenceClickListener(null);
    }
  });

  preference.setOnPreferenceClickListener(listener);
}
 
Example 3
Source File: AppearanceSettingsFragment.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void initIconProviderPreference() {
    Preference iconProvider = findPreference(getString(R.string.key_icon_provider));
    iconProvider.setSummary(ResourcesProviderFactory.getNewInstance().getProviderName());
    
    iconProvider.setOnPreferenceClickListener(preference -> {
        ProvidersPreviewerDialog dialog = new ProvidersPreviewerDialog();
        dialog.setOnIconProviderChangedListener(iconProvider1 -> {
            getSettingsOptionManager().setIconProvider(iconProvider1);
            PreferenceManager.getDefaultSharedPreferences(requireActivity())
                    .edit()
                    .putString(getString(R.string.key_icon_provider), iconProvider1)
                    .apply();
            initIconProviderPreference();
            SnackbarUtils.showSnackbar(
                    (GeoActivity) requireActivity(), 
                    getString(R.string.feedback_refresh_ui_after_refresh)
            );
        });
        dialog.show(getParentFragmentManager(), null);
        return true;
    });
}
 
Example 4
Source File: TalkBackPreferencesActivity.java    From talkback with Apache License 2.0 6 votes vote down vote up
private void assignFeedbackIntentToPreference(int preferenceId) {
  Preference pref = findPreferenceByResId(preferenceId);
  if (pref == null) {
    return;
  }
  // We are not supporting feedback on the Wear device itself for initial launch of
  // TalkBack on Wear.
  if (!isWatch
      && HelpAndFeedbackUtils.supportsHelpAndFeedback(getActivity().getApplicationContext())) {
    pref.setTitle(R.string.title_pref_help_and_feedback);
    pref.setOnPreferenceClickListener(
        new Preference.OnPreferenceClickListener() {
          @Override
          public boolean onPreferenceClick(Preference preference) {
            HelpAndFeedbackUtils.launchHelpAndFeedback(getActivity());
            return true;
          }
        });
  } else {
    pref.setTitle(R.string.title_pref_help);
    assignWebIntentToPreference(preferenceId, HELP_URL);
  }
}
 
Example 5
Source File: AppProtectionPreferenceFragment.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onResume() {
  super.onResume();
  ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.preferences__privacy);

  initializePassphraseLockTriggerSummary();
  initializePassphraseTimeoutSummary();

  Preference             signalPinCreateChange   = this.findPreference(TextSecurePreferences.SIGNAL_PIN_CHANGE);
  SwitchPreferenceCompat signalPinReminders      = (SwitchPreferenceCompat) this.findPreference(PinValues.PIN_REMINDERS_ENABLED);
  SwitchPreferenceCompat registrationLockV2      = (SwitchPreferenceCompat) this.findPreference(KbsValues.V2_LOCK_ENABLED);

  if (SignalStore.kbsValues().hasPin()) {
    signalPinCreateChange.setOnPreferenceClickListener(new KbsPinUpdateListener());
    signalPinCreateChange.setTitle(R.string.preferences_app_protection__change_your_pin);
    registrationLockV2.setEnabled(true);
  } else {
    signalPinCreateChange.setOnPreferenceClickListener(new KbsPinCreateListener());
    signalPinCreateChange.setTitle(R.string.preferences_app_protection__create_a_pin);
    signalPinReminders.setEnabled(false);
    registrationLockV2.setEnabled(false);
  }
}
 
Example 6
Source File: BluetoothPreferences.java    From openScale with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.bluetooth_preferences, rootKey);

    setHasOptionsMenu(true);

    btScanner = (Preference) findPreference(PREFERENCE_KEY_BLUETOOTH_SCANNER);

    btScanner.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            NavDirections action = BluetoothPreferencesDirections.actionNavBluetoothPreferencesToNavBluetoothSettings();
            Navigation.findNavController(getActivity(), R.id.nav_host_fragment).navigate(action);
            return true;
        }
    });

    btScanner.setSummary(getCurrentDeviceName());
}
 
Example 7
Source File: WatchOnlyPreferenceFragment.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) {
    super.onCreatePreferences(savedInstanceState, rootKey);
    addPreferencesFromResource(R.xml.preference_watchonly);
    setHasOptionsMenu(true);

    // Network & Logout
    final Preference logout = find(PrefKeys.LOGOUT);
    logout.setTitle(getString(R.string.id_s_network, getNetwork().getName()));
    logout.setSummary(UI.getColoredString(
                          getString(R.string.id_log_out), ContextCompat.getColor(getContext(), R.color.red)));
    logout.setOnPreferenceClickListener(preference -> {
        logout.setEnabled(false);
        logout();
        return false;
    });

    // Version
    final Preference version = find("version");
    version.setSummary(String.format("%s %s",
                                     getString(R.string.app_name),
                                     getString(R.string.id_version_1s_2s,
                                               BuildConfig.VERSION_NAME,
                                               BuildConfig.BUILD_TYPE)));

    // Terms of service
    final Preference termsOfUse = find(PrefKeys.TERMS_OF_USE);
    termsOfUse.setOnPreferenceClickListener(preference -> openURI("https://blockstream.com/green/terms/"));

    // Privacy policy
    final Preference privacyPolicy = find(PrefKeys.PRIVACY_POLICY);
    privacyPolicy.setOnPreferenceClickListener(preference -> openURI("https://blockstream.com/green/privacy/"));

    ((Preference) find("logout")).setOnPreferenceClickListener(this);
}
 
Example 8
Source File: MainConfigurablePreferences.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void setupPrefClickListeners() {
    configureDevPreferencesButton();

    Preference analyticsButton = findPreference(DISABLE_ANALYTICS);
    if (MainConfigurablePreferences.isAnalyticsEnabled()) {
        analyticsButton.setOnPreferenceClickListener(preference -> {
            showAnalyticsOptOutDialog();
            return true;
        });
    } else {
        getPreferenceScreen().removePreference(analyticsButton);
    }
}
 
Example 9
Source File: SettingsFragment.java    From android-notification-log with MIT License 5 votes vote down vote up
@Override
public void onCreatePreferences(Bundle bundle, String s) {
	addPreferencesFromResource(R.xml.preferences);

	PreferenceManager pm = getPreferenceManager();

	prefStatus = pm.findPreference(Const.PREF_STATUS);
	if(prefStatus != null) {
		prefStatus.setOnPreferenceClickListener(preference -> {
			startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
			return true;
		});
	}

	prefBrowse = pm.findPreference(Const.PREF_BROWSE);
	if(prefBrowse != null) {
		prefBrowse.setOnPreferenceClickListener(preference -> {
			startActivity(new Intent(getActivity(), BrowseActivity.class));
			return true;
		});
	}

	prefText    = pm.findPreference(Const.PREF_TEXT);
	prefOngoing = pm.findPreference(Const.PREF_ONGOING);

	Preference prefAbout = pm.findPreference(Const.PREF_ABOUT);
	if(prefAbout != null) {
		prefAbout.setOnPreferenceClickListener(preference -> {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("https://github.com/interactionlab/android-notification-log"));
			startActivity(intent);
			return true;
		});
	}

	Preference prefVersion = pm.findPreference(Const.PREF_VERSION);
	if(prefVersion != null) {
		prefVersion.setSummary(BuildConfig.VERSION_NAME + (Const.DEBUG ? " dev" : ""));
	}
}
 
Example 10
Source File: SettingsFragment.java    From ground-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
  setPreferencesFromResource(R.xml.preferences, rootKey);
  for (String key : Keys.ALL_KEYS) {
    Preference preference = findPreference(key);
    if (preference == null) {
      throw new IllegalArgumentException("Key not found in preferences.xml: " + key);
    }

    preference.setOnPreferenceChangeListener(this);
    preference.setOnPreferenceClickListener(this);
  }
}
 
Example 11
Source File: ChatsPreferenceFragment.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(Bundle paramBundle) {
  super.onCreate(paramBundle);

  mediaQuality = (ListPreference) this.findPreference("pref_compression");
  mediaQuality.setOnPreferenceChangeListener((preference, newValue) -> {
    updateListSummary(preference, newValue);
    dcContext.setConfigInt(DcHelper.CONFIG_MEDIA_QUALITY, Util.objectToInt(newValue));
    return true;
  });

  showEmails = (ListPreference) this.findPreference("pref_show_emails");
  showEmails.setOnPreferenceChangeListener((preference, newValue) -> {
    updateListSummary(preference, newValue);
    dcContext.setConfigInt(CONFIG_SHOW_EMAILS, Util.objectToInt(newValue));
    return true;
  });

  readReceiptsCheckbox = (CheckBoxPreference) this.findPreference("pref_read_receipts");
  readReceiptsCheckbox.setOnPreferenceChangeListener(new ReadReceiptToggleListener());

  this.findPreference("preference_category_blocked").setOnPreferenceClickListener(new BlockedContactsClickListener());

  Preference backup = this.findPreference("pref_backup");
  backup.setOnPreferenceClickListener(new BackupListener());

  autoDelDevice = findPreference("autodel_device");
  autoDelDevice.setOnPreferenceChangeListener(new AutodelChangeListener("delete_device_after"));

  autoDelServer = findPreference("autodel_server");
  autoDelServer.setOnPreferenceChangeListener(new AutodelChangeListener("delete_server_after"));
}
 
Example 12
Source File: MainConfigurablePreferences.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private void configureDevPreferencesButton() {
    Preference developerSettingsButton = findPreference(DEVELOPER_SETTINGS);
    if (DeveloperPreferences.isSuperuserEnabled()) {
        developerSettingsButton.setOnPreferenceClickListener(preference -> {
            startDeveloperOptions();
            return true;
        });
    } else {
        getPreferenceScreen().removePreference(developerSettingsButton);
    }
}
 
Example 13
Source File: LockScreenPolicyFragment.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
/**
 * Set an initial value. Updates the summary to match.
 */
private void setup(String key, Object adminSetting) {
    final Preference pref = findPreference(key);
    final DpcPreferenceBase dpcPref = (DpcPreferenceBase) pref;

    // Disable preferences that don't apply to the parent profile
    dpcPref.setCustomConstraint(
            () -> Keys.NOT_APPLICABLE_TO_PARENT.contains(key) && isParentProfileInstance()
                    ? R.string.not_for_parent_profile
                    : NO_CUSTOM_CONSTRIANT
    );

    // We do not allow user to add trust agent config in pre-N devices in managed profile.
    if (Util.SDK_INT < VERSION_CODES.N && key.equals(Keys.SET_TRUST_AGENT_CONFIG)) {
        dpcPref.setAdminConstraint(DpcPreferenceHelper.ADMIN_DEVICE_OWNER);
        return;
    }

    // Set up initial state and possibly a descriptive summary of said state.
    if (pref instanceof EditTextPreference) {
        String stringValue = (adminSetting != null ? adminSetting.toString() : null);
        if (adminSetting instanceof Number && "0".equals(stringValue)) {
            stringValue = null;
        }
        ((EditTextPreference) pref).setText(stringValue);
        pref.setSummary(stringValue);
    } else if (pref instanceof TwoStatePreference) {
        ((TwoStatePreference) pref).setChecked((Boolean) adminSetting);
    }

    // Start listening for change events.
    pref.setOnPreferenceChangeListener(this);
    pref.setOnPreferenceClickListener(this);
}
 
Example 14
Source File: SettingsFragment.java    From XposedSmsCode with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    addPreferencesFromResource(R.xml.settings);

    // general group
    if (!ModuleUtils.isModuleEnabled()) {
        Preference enablePref = findPreference(PrefConst.KEY_ENABLE);
        // enablePref.setEnabled(false);
        enablePref.setSummary(R.string.pref_enable_summary_alt);
    }

    findPreference(PrefConst.KEY_HIDE_LAUNCHER_ICON).setOnPreferenceChangeListener(this);

    findPreference(PrefConst.KEY_CHOOSE_THEME).setOnPreferenceClickListener(this);

    findPreference(PrefConst.KEY_APP_BLOCK_ENTRY).setOnPreferenceClickListener(this);
    // general group end

    // experimental group
    // experimental group end

    // code message group
    findPreference(PrefConst.KEY_CODE_RULES).setOnPreferenceClickListener(this);
    findPreference(PrefConst.KEY_SMSCODE_TEST).setOnPreferenceClickListener(this);
    // code message group end

    // code records group
    Preference recordsEntryPref = findPreference(PrefConst.KEY_ENTRY_CODE_RECORDS);
    recordsEntryPref.setOnPreferenceClickListener(this);
    initRecordEntryPreference(recordsEntryPref);
    // code records group end

    // others group
    findPreference(PrefConst.KEY_VERBOSE_LOG_MODE).setOnPreferenceChangeListener(this);
    // others group end

    // about group
    // version info preference
    Preference versionPref = findPreference(PrefConst.KEY_VERSION);
    versionPref.setOnPreferenceClickListener(this);
    showVersionInfo(versionPref);
    findPreference(PrefConst.KEY_JOIN_QQ_GROUP).setOnPreferenceClickListener(this);
    findPreference(PrefConst.KEY_SOURCE_CODE).setOnPreferenceClickListener(this);
    findPreference(PrefConst.KEY_GET_ALIPAY_PACKET).setOnPreferenceClickListener(this);
    findPreference(PrefConst.KEY_DONATE_BY_ALIPAY).setOnPreferenceClickListener(this);
    // about group end
}
 
Example 15
Source File: AdvancedPreferenceFragment.java    From Infinity-For-Reddit with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.advanced_preferences, rootKey);

    ((Infinity) activity.getApplication()).getAppComponent().inject(this);

    Preference deleteSubredditsPreference = findPreference(SharedPreferencesUtils.DELETE_ALL_SUBREDDITS_DATA_IN_DATABASE);
    Preference deleteUsersPreference = findPreference(SharedPreferencesUtils.DELETE_ALL_USERS_DATA_IN_DATABASE);
    Preference deleteSortTypePreference = findPreference(SharedPreferencesUtils.DELETE_ALL_SORT_TYPE_DATA_IN_DATABASE);
    Preference deletePostLaoutPreference = findPreference(SharedPreferencesUtils.DELETE_ALL_POST_LAYOUT_DATA_IN_DATABASE);
    Preference deleteAllThemesPreference = findPreference(SharedPreferencesUtils.DELETE_ALL_THEMES_IN_DATABASE);
    Preference resetAllSettingsPreference = findPreference(SharedPreferencesUtils.RESET_ALL_SETTINGS);

    if (deleteSubredditsPreference != null) {
        deleteSubredditsPreference.setOnPreferenceClickListener(preference -> {
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> new DeleteAllSubredditsAsyncTask(mRedditDataRoomDatabase,
                                    () -> Toast.makeText(activity, R.string.delete_all_subreddits_success, Toast.LENGTH_SHORT).show()).execute())
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        });
    }

    if (deleteUsersPreference != null) {
        deleteUsersPreference.setOnPreferenceClickListener(preference -> {
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> new DeleteAllUsersAsyncTask(mRedditDataRoomDatabase,
                                    () -> Toast.makeText(activity, R.string.delete_all_users_success, Toast.LENGTH_SHORT).show()).execute())
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        });
    }

    if (deleteSortTypePreference != null) {
        deleteSortTypePreference.setOnPreferenceClickListener(preference -> {
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> new DeleteAllSortTypesAsyncTask(mSharedPreferences, mSortTypeSharedPreferences, () -> {
                                Toast.makeText(activity, R.string.delete_all_sort_types_success, Toast.LENGTH_SHORT).show();
                                EventBus.getDefault().post(new RecreateActivityEvent());
                            }).execute())
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        });
    }

    if (deletePostLaoutPreference != null) {
        deletePostLaoutPreference.setOnPreferenceClickListener(preference -> {
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> new DeleteAllPostLayoutsAsyncTask(mSharedPreferences, mPostLayoutSharedPreferences, () -> {
                                Toast.makeText(activity, R.string.delete_all_post_layouts_success, Toast.LENGTH_SHORT).show();
                                EventBus.getDefault().post(new RecreateActivityEvent());
                            }).execute())
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        });
    }

    if (deleteAllThemesPreference != null) {
        deleteAllThemesPreference.setOnPreferenceClickListener(preference -> {
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> new DeleteAllThemesAsyncTask(mRedditDataRoomDatabase, lightThemeSharedPreferences,
                                    darkThemeSharedPreferences, amoledThemeSharedPreferences, () -> {
                                Toast.makeText(activity, R.string.delete_all_themes_success, Toast.LENGTH_SHORT).show();
                                EventBus.getDefault().post(new RecreateActivityEvent());
                            }).execute())
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        });
    }

    if (resetAllSettingsPreference != null) {
        resetAllSettingsPreference.setOnPreferenceClickListener(preference -> {
            new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
                    .setTitle(R.string.are_you_sure)
                    .setPositiveButton(R.string.yes, (dialogInterface, i)
                            -> {
                        mSharedPreferences.edit().clear().apply();
                        Toast.makeText(activity, R.string.reset_all_settings_success, Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new RecreateActivityEvent());
                    })
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        });
    }
}
 
Example 16
Source File: SettingsFragment.java    From vinyl-cast with MIT License 4 votes vote down vote up
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    Timber.d("onCreatePreferences");

    setPreferencesFromResource(R.xml.preferences, rootKey);

    AudioDevicePreference recordingDevicePref = findPreference(R.string.prefs_key_recording_device_id);
    AudioDevicePreference playbackDevicePref = findPreference(R.string.prefs_key_local_playback_device_id);
    CheckBoxPreference lowLatencyPref = findPreference(R.string.prefs_key_low_latency);
    ListPreference audioEncodingPref = findPreference(R.string.prefs_key_audio_encoding);
    Preference feedbackPref = findPreference(R.string.prefs_key_feedback);
    Preference androidApiLevelPref = findPreference(R.string.prefs_key_android_api_level);
    Preference appVersionPref = findPreference(R.string.prefs_key_app_version);

    if (recordingDevicePref != null) {
        recordingDevicePref.setDirectionType(AudioManager.GET_DEVICES_INPUTS);
        recordingDevicePref.setOnPreferenceClickListener(disabledPreferenceClickListener);
        recordingDevicePref.setOnPreferenceChangeListener(audioDeviceOnChangeListener);
    }
    if (playbackDevicePref != null) {
        playbackDevicePref.setDirectionType(AudioManager.GET_DEVICES_OUTPUTS);
        playbackDevicePref.setOnPreferenceClickListener(disabledPreferenceClickListener);
        playbackDevicePref.setOnPreferenceChangeListener(audioDeviceOnChangeListener);
    }
    if (lowLatencyPref != null) {
        lowLatencyPref.setOnPreferenceClickListener(disabledPreferenceClickListener);
    }
    if (audioEncodingPref != null) {
        audioEncodingPref.setEntries(R.array.prefs_audio_encoding_entries);
        audioEncodingPref.setEntryValues(R.array.prefs_audio_encoding_entry_values);
        audioEncodingPref.setOnPreferenceClickListener(disabledPreferenceClickListener);
    }
    if (feedbackPref != null && BuildConfig.FLAVOR.equals("playstore")) {
        feedbackPref.setVisible(true);
        feedbackPref.setOnPreferenceClickListener(preference -> {
            try {
                // Use reflection to get Instabug since only available in playstore product flavor
                Class instabugClazz = Class.forName("com.instabug.library.Instabug");
                if (binder != null) {
                    //Instabug.setUserAttribute("Audio API", getAudioApiVersionString());
                    Method setUserAttributeMethod = instabugClazz.getMethod("setUserAttribute", String.class, String.class);
                    setUserAttributeMethod.invoke(null, "Audio API", getAudioApiVersionString());
                }
                //Instabug.show();
                Method showMethod = instabugClazz.getMethod("show");
                showMethod.invoke(null);
            } catch (ReflectiveOperationException e) {
                e.printStackTrace();
            }
            return true;
        });
    }
    if (androidApiLevelPref != null) {
        androidApiLevelPref.setSummaryProvider(preference ->
                Integer.toString(Build.VERSION.SDK_INT)
        );
    }
    if (appVersionPref != null) {
        appVersionPref.setSummaryProvider(preference ->
                String.format(Locale.getDefault(), "%s (%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
        );
    }

    // set initial state of dynamic preferences
    updateDynamicPreferences();
}
 
Example 17
Source File: MuzeiSettingsFragment.java    From Mysplash with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.perference_muzei);

    MuzeiOptionManager manager = MuzeiOptionManager.getInstance(requireActivity());

    // muzei source.
    ListPreference source = findPreference(getString(R.string.key_muzei_source));
    source.setSummary(
            getNameByValue(
                    manager.getSource(),
                    R.array.muzei_sources,
                    R.array.muzei_source_values
            )
    );
    source.setOnPreferenceChangeListener((preference, newValue) -> {
        manager.setSource((String) newValue);
        preference.setSummary(
                getNameByValue(
                        manager.getSource(),
                        R.array.muzei_sources,
                        R.array.muzei_source_values
                )
        );

        findPreference(getString(R.string.key_muzei_collection_source)).setEnabled(
                manager.getSource().equals(MuzeiOptionManager.SOURCE_COLLECTIONS)
        );
        return true;
    });

    // screen size.
    SwitchPreference screenSizeImage = findPreference(getString(R.string.key_muzei_screen_size_image));
    int[] size = MuzeiUpdateHelper.getScreenSize(requireActivity());
    screenSizeImage.setSummaryOn(size[1] + "×" + size[0]);
    screenSizeImage.setSummaryOff(R.string.muzei_settings_title_screen_size_image_summary_off);
    screenSizeImage.setOnPreferenceChangeListener((preference, newValue) -> {
        manager.setScreenSizeImage((Boolean) newValue);
        return true;
    });

    // cache mode.
    ListPreference cacheMode = findPreference(getString(R.string.key_muzei_cache_mode));
    cacheMode.setSummary(
            getNameByValue(
                    manager.getCacheMode(),
                    R.array.muzei_cache_modes,
                    R.array.muzei_cache_mode_values
            )
    );
    cacheMode.setOnPreferenceChangeListener((preference, newValue) -> {
        manager.setCacheMode((String) newValue);
        preference.setSummary(
                getNameByValue(
                        manager.getCacheMode(),
                        R.array.muzei_cache_modes,
                        R.array.muzei_cache_mode_values
                )
        );
        return true;
    });

    // collections.
    Preference collectionSource = findPreference(getString(R.string.key_muzei_collection_source));
    collectionSource.setEnabled(manager.getSource().equals(MuzeiOptionManager.SOURCE_COLLECTIONS));
    collectionSource.setOnPreferenceClickListener(preference -> {
        ComponentFactory.getMuzeiService()
                .startMuzeiCollectionSourceConfigActivity(requireActivity());
        return true;
    });

    // query.
    Preference query = findPreference(getString(R.string.key_muzei_query));
    query.setSummary(manager.getQuery());
    query.setOnPreferenceClickListener(preference -> {
        MuzeiQueryDialog dialog = new MuzeiQueryDialog();
        dialog.setOnQueryChangedListener(query1 -> {
            MuzeiOptionManager.updateQuery(requireActivity(), query1);
            Preference q = findPreference(getString(R.string.key_muzei_query));
            q.setSummary(MuzeiOptionManager.getInstance(requireActivity()).getQuery());
        });
        dialog.show(requireFragmentManager(), null);
        return true;
    });
}
 
Example 18
Source File: AdvancedActionsPreferences.java    From commcare-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void setupPrefClickListeners() {
    Preference reportProblemButton = findPreference(REPORT_PROBLEM);
    reportProblemButton.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.REPORT_PROBLEM);
        startReportActivity();
        return true;
    });

    Preference validateMediaButton = findPreference(VALIDATE_MEDIA);
    validateMediaButton.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.VALIDATE_MEDIA);
        startValidationActivity();
        return true;
    });

    Preference wifiDirectButton = findPreference(WIFI_DIRECT);
    if (hasP2p()) {
        wifiDirectButton.setOnPreferenceClickListener(preference -> {
            FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                    AnalyticsParamValue.WIFI_DIRECT);
            startWifiDirect();
            return true;
        });
    } else {
        getPreferenceScreen().removePreference(wifiDirectButton);
    }

    Preference dumpFormsButton = findPreference(DUMP_FORMS);
    dumpFormsButton.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.MANAGE_SD);
        startFormDump();
        return true;
    });

    Preference connectionTestButton = findPreference(CONNECTION_TEST);
    connectionTestButton.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.CONNECTION_TEST);
        startConnectionTest();
        return true;
    });

    Preference clearDataButton = findPreference(CLEAR_USER_DATA);
    clearDataButton.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.CLEAR_USER_DATA);
        clearUserData(getActivity());
        return true;
    });

    Preference clearSavedSessionButton = findPreference(CLEAR_SAVED_SESSION);
    if (DevSessionRestorer.savedSessionPresent()) {
        clearSavedSessionButton.setOnPreferenceClickListener(preference -> {
            FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                    AnalyticsParamValue.CLEAR_SAVED_SESSION);
            DevSessionRestorer.clearSession();
            return true;
        });
    } else {
        getPreferenceScreen().removePreference(clearSavedSessionButton);
    }


    Preference forceSubmitButton = findPreference(FORCE_LOG_SUBMIT);
    forceSubmitButton.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.FORCE_LOG_SUBMISSION);
        CommCareUtil.triggerLogSubmission(getActivity(), false);
        return true;
    });

    Preference recoveryModeButton = findPreference(RECOVERY_MODE);
    recoveryModeButton.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.RECOVERY_MODE);
        startRecoveryMode();
        return true;
    });

    Preference clearAppReleaseTimePref = findPreference(DISABLE_PRE_UPDATE_SYNC);
    clearAppReleaseTimePref.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.DISABLE_PRE_UPDATE_SYNC);
        HiddenPreferences.enableBypassPreUpdateSync(true);
        Toast.makeText(getActivity(),R.string.success, Toast.LENGTH_SHORT).show();
        return true;
    });

    Preference rateLimitPopup = findPreference(ENABLE_RATE_LIMIT_POPUP);
    rateLimitPopup.setOnPreferenceClickListener(preference -> {
        FirebaseAnalyticsUtil.reportAdvancedActionSelected(
                AnalyticsParamValue.ENABLE_RATE_LIMIT_POPUP);
        HiddenPreferences.disableRateLimitPopup(false);
        Toast.makeText(getActivity(),R.string.success, Toast.LENGTH_SHORT).show();
        return true;
    });
}
 
Example 19
Source File: PreferencesTorFragment.java    From InviZible with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setRetainInstance(true);

    addPreferencesFromResource(R.xml.preferences_tor);

    if (appVersion.endsWith("p")) {
        changePreferencesForGPVersion();
    }

    ArrayList<Preference> preferences = new ArrayList<>();

    preferences.add(findPreference("VirtualAddrNetwork"));
    preferences.add(findPreference("AvoidDiskWrites"));
    preferences.add(findPreference("ConnectionPadding"));
    preferences.add(findPreference("ReducedConnectionPadding"));
    preferences.add(findPreference("ExcludeExitNodes"));
    preferences.add(findPreference("ExitNodes"));
    preferences.add(findPreference("ExcludeNodes"));
    preferences.add(findPreference("EntryNodes"));
    preferences.add(findPreference("StrictNodes"));
    preferences.add(findPreference("FascistFirewall"));
    preferences.add(findPreference("NewCircuitPeriod"));
    preferences.add(findPreference("MaxCircuitDirtiness"));
    preferences.add(findPreference("EnforceDistinctSubnets"));
    preferences.add(findPreference("Enable SOCKS proxy"));
    preferences.add(findPreference("SOCKSPort"));
    preferences.add(findPreference("Enable HTTPTunnel"));
    preferences.add(findPreference("HTTPTunnelPort"));
    preferences.add(findPreference("Enable Transparent proxy"));
    preferences.add(findPreference("TransPort"));
    preferences.add(findPreference("Enable DNS"));
    preferences.add(findPreference("DNSPort"));
    preferences.add(findPreference("ClientUseIPv4"));
    preferences.add(findPreference("ClientUseIPv6"));
    preferences.add(findPreference("pref_tor_snowflake_stun"));
    preferences.add(findPreference("pref_tor_isolate_dest_address"));
    preferences.add(findPreference("pref_tor_isolate_dest_port"));

    for (Preference preference : preferences) {
        if (preference != null) {
            preference.setOnPreferenceChangeListener(this);
        } else if (!appVersion.startsWith("g")) {
            Log.e(LOG_TAG, "PreferencesTorFragment preference is null exception");
        }
    }

    Preference editTorConfDirectly = findPreference("editTorConfDirectly");
    if (editTorConfDirectly != null) {
        editTorConfDirectly.setOnPreferenceClickListener(this);
    }

    Preference cleanTorFolder = findPreference("cleanTorFolder");
    if (cleanTorFolder != null) {
        cleanTorFolder.setOnPreferenceClickListener(this);
    }

    if (getArguments() != null) {
        key_tor = getArguments().getStringArrayList("key_tor");
        val_tor = getArguments().getStringArrayList("val_tor");
        key_tor_orig = new ArrayList<>(key_tor);
        val_tor_orig = new ArrayList<>(val_tor);
    }
}
 
Example 20
Source File: SettingsFragment.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

    addPreferencesFromResource(R.xml.settings);
    if (getArguments() != null && getArguments().getBoolean("showKerahatDuration"))
        setPreferenceScreen((PreferenceScreen) findPreference("kerahatDuration"));
    else {
   /*     findPreference("language").setIcon(MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.TRANSLATE)
                .setColor(getResources().getColor(R.color.foregroundSecondary)).build());
        findPreference("arabicNames").setIcon(MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.CLOCK_OUT)
                .setColor(getResources().getColor(R.color.foregroundSecondary)).build());
        findPreference("digits").setIcon(MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.NUMERIC)
                .setColor(getResources().getColor(R.color.foregroundSecondary)).build());
        findPreference("calendarIntegration").setIcon(
                MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.CALENDAR)
                        .setColor(getResources().getColor(R.color.foregroundSecondary)).build());
        findPreference("kerahatDuration").setIcon(
                MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.CLOCK_ALERT)
                        .setColor(getResources().getColor(R.color.foregroundSecondary)).build());
     */

        findPreference("numbers").setOnPreferenceChangeListener(this);
        findPreference("backupRestore").setOnPreferenceClickListener(this);
        findPreference("calendarIntegration").setOnPreferenceChangeListener(this);
        findPreference("ongoingIcon").setOnPreferenceClickListener(this);
        findPreference("ongoingNumber").setOnPreferenceClickListener(this);
        findPreference("kerahatDuration").setOnPreferenceClickListener(this);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            findPreference("ongoingNumber").setEnabled(false);
        }

        if (Build.VERSION.SDK_INT < 24)
            findPreference("showLegacyWidgets").setEnabled(false);


        findPreference("arabicNames").setEnabled(!new Locale("ar").getLanguage().equals(LocaleUtils.getLocale().getLanguage()));

        ListPreference lang = (ListPreference) findPreference("language");
        lang.setOnPreferenceChangeListener(this);

        List<LocaleUtils.Translation> languages = LocaleUtils.getSupportedLanguages(getActivity());
        CharSequence[] entries = new CharSequence[languages.size()];
        CharSequence[] values = new CharSequence[languages.size()];
        for (int i = 0; i < languages.size(); i++) {
            LocaleUtils.Translation trans = languages.get(i);
            entries[i] = trans.getDisplayText();
            values[i] = trans.getLanguage();
        }
        lang.setEntries(entries);
        lang.setEntryValues(values);


        int[][] colors = {{0, 0},
                {0xFFFFFFFF, 0xFF333333},
                {0xFFDDDDDD, 0xFF222222},
                {0xFFBBBBBB, 0xFF111111},
                {0xFF999999, 0xFF000000},
                {0xFF666666, 0xFFFFFFFF},
                {0xFF444444, 0xFFEEEEEE},
                {0xFF222222, 0xFFDDDDDD},
                {0xFF000000, 0xFFCCCCCC}
        };

        Preference ongoingColor = findPreference("ongoingColor");

        ongoingColor.setOnPreferenceClickListener(e -> {
            AlertDialog.Builder dlg = new AlertDialog.Builder(getActivity());
            dlg.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.select_dialog_singlechoice) {
                @Override
                public int getCount() {
                    return colors.length;
                }

                @NonNull
                @Override
                public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                    CheckedTextView v = (CheckedTextView) LayoutInflater.from(getContext()).inflate(android.R.layout.select_dialog_singlechoice, parent, false);
                    int p = (int) Utils.convertDpToPixel(getContext(), 4);
                    v.setPadding(4 * p, p, 4 * p, p);
                    v.setText(position == 0 ? "System" : "Abc");
                    v.setBackgroundColor(position == 0 ? Color.WHITE : colors[position][0]);
                    v.setTextColor(position == 0 ? Color.BLACK : colors[position][1]);
                    v.setChecked(colors[position][0] == Preferences.ONGOING_BG_COLOR.get() && colors[position][1] == Preferences.ONGOING_TEXT_COLOR.get());
                    return v;
                }
            }, (dialog, which) -> {
                Preferences.ONGOING_BG_COLOR.set(colors[which][0]);
                Preferences.ONGOING_TEXT_COLOR.set(colors[which][1]);
            });
            dlg.show();
            return true;

        });
    }

}