Example usage for android.preference ListPreference findIndexOfValue

List of usage examples for android.preference ListPreference findIndexOfValue

Introduction

In this page you can find the example usage for android.preference ListPreference findIndexOfValue.

Prototype

public int findIndexOfValue(String value) 

Source Link

Document

Returns the index of the given value (in the entry values array).

Usage

From source file:it.feio.android.omninotes.SettingsFragment.java

@SuppressWarnings("deprecation")
@Override/*  w w  w. j av a2  s .  c o  m*/
public void onResume() {
    super.onResume();

    // Export notes
    Preference export = findPreference("settings_export_data");
    if (export != null) {
        export.setOnPreferenceClickListener(arg0 -> {

            // Inflate layout
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.dialog_backup_layout, null);

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    () -> export(v));

            return false;
        });
    }

    // Import notes
    Preference importData = findPreference("settings_import_data");
    if (importData != null) {
        importData.setOnPreferenceClickListener(arg0 -> {

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    this::importNotes);

            return false;
        });
    }

    // Import notes from Springpad export zip file
    Preference importFromSpringpad = findPreference("settings_import_from_springpad");
    if (importFromSpringpad != null) {
        importFromSpringpad.setOnPreferenceClickListener(arg0 -> {
            Intent intent;
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("application/zip");
            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            startActivityForResult(intent, SPRINGPAD_IMPORT);
            return false;
        });
    }

    //      Preference syncWithDrive = findPreference("settings_backup_drive");
    //      importFromSpringpad.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //         @Override
    //         public boolean onPreferenceClick(Preference arg0) {
    //            Intent intent;
    //            intent = new Intent(Intent.ACTION_GET_CONTENT);
    //            intent.addCategory(Intent.CATEGORY_OPENABLE);
    //            intent.setType("application/zip");
    //            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
    //               Crouton.makeText(getActivity(), R.string.feature_not_available_on_this_device,
    // ONStyle.ALERT).show();
    //               return false;
    //            }
    //            startActivityForResult(intent, SPRINGPAD_IMPORT);
    //            return false;
    //         }
    //      });

    // Swiping action
    final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash");
    if (swipeToTrash != null) {
        if (prefs.getBoolean("settings_swipe_to_trash", false)) {
            swipeToTrash.setChecked(true);
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
        } else {
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            swipeToTrash.setChecked(false);
        }
        swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((Boolean) newValue) {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
            } else {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            }
            swipeToTrash.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show uncategorized notes in menu
    final SwitchPreference showUncategorized = (SwitchPreference) findPreference(
            Constants.PREF_SHOW_UNCATEGORIZED);
    if (showUncategorized != null) {
        showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> {
            showUncategorized.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show Automatically adds location to new notes
    final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION);
    if (autoLocation != null) {
        autoLocation.setOnPreferenceChangeListener((preference, newValue) -> {
            autoLocation.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Maximum video attachment size
    final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size");
    if (maxVideoSize != null) {
        String maxVideoSizeValue = prefs.getString("settings_max_video_size", getString(R.string.not_set));
        maxVideoSize.setSummary(
                getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(maxVideoSizeValue));
        maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> {
            maxVideoSize.setSummary(
                    getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(newValue));
            prefs.edit().putString("settings_max_video_size", newValue.toString()).commit();
            return false;
        });
    }

    // Set notes' protection password
    Preference password = findPreference("settings_password");
    if (password != null) {
        password.setOnPreferenceClickListener(preference -> {
            Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class);
            startActivity(passwordIntent);
            return false;
        });
    }

    // Use password to grant application access
    final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access");
    if (passwordAccess != null) {
        if (prefs.getString(Constants.PREF_PASSWORD, null) == null) {
            passwordAccess.setEnabled(false);
            passwordAccess.setChecked(false);
        } else {
            passwordAccess.setEnabled(true);
        }
        passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> {
            BaseActivity.requestPassword(getActivity(), passwordConfirmed -> {
                if (passwordConfirmed) {
                    passwordAccess.setChecked((Boolean) newValue);
                }
            });
            return false;
        });
    }

    // Languages
    ListPreference lang = (ListPreference) findPreference("settings_language");
    if (lang != null) {
        String languageName = getResources().getConfiguration().locale.getDisplayName();
        lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale)
                + languageName.substring(1, languageName.length()));
        lang.setOnPreferenceChangeListener((preference, value) -> {
            OmniNotes.updateLanguage(getActivity(), value.toString());
            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
            return false;
        });
    }

    // Text size
    final ListPreference textSize = (ListPreference) findPreference("settings_text_size");
    if (textSize != null) {
        int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default"));
        String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex];
        textSize.setSummary(textSizeString);
        textSize.setOnPreferenceChangeListener((preference, newValue) -> {
            int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString());
            String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1];
            textSize.setSummary(checklistString);
            prefs.edit().putString("settings_text_size", newValue.toString()).commit();
            textSize.setValueIndex(textSizeIndex1);
            return false;
        });
    }

    // Application's colors
    final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app");
    if (colorsApp != null) {
        int colorsAppIndex = colorsApp
                .findIndexOfValue(prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex];
        colorsApp.setSummary(colorsAppString);
        colorsApp.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString());
            String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1];
            colorsApp.setSummary(colorsAppString1);
            prefs.edit().putString("settings_colors_app", newValue.toString()).commit();
            colorsApp.setValueIndex(colorsAppIndex1);
            return false;
        });
    }

    // Checklists
    final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior");
    if (checklist != null) {
        int checklistIndex = checklist
                .findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0"));
        String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex];
        checklist.setSummary(checklistString);
        checklist.setOnPreferenceChangeListener((preference, newValue) -> {
            int checklistIndex1 = checklist.findIndexOfValue(newValue.toString());
            String checklistString1 = getResources()
                    .getStringArray(R.array.checked_items_behavior)[checklistIndex1];
            checklist.setSummary(checklistString1);
            prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).commit();
            checklist.setValueIndex(checklistIndex1);
            return false;
        });
    }

    // Widget's colors
    final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget");
    if (colorsWidget != null) {
        int colorsWidgetIndex = colorsWidget
                .findIndexOfValue(prefs.getString("settings_colors_widget", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex];
        colorsWidget.setSummary(colorsWidgetString);
        colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString());
            String colorsWidgetString1 = getResources()
                    .getStringArray(R.array.colors_widget)[colorsWidgetIndex1];
            colorsWidget.setSummary(colorsWidgetString1);
            prefs.edit().putString("settings_colors_widget", newValue.toString()).commit();
            colorsWidget.setValueIndex(colorsWidgetIndex1);
            return false;
        });
    }

    // Notification snooze delay
    final EditTextPreference snoozeDelay = (EditTextPreference) findPreference(
            "settings_notification_snooze_delay");
    if (snoozeDelay != null) {
        String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT);
        snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze;
        snoozeDelay.setSummary(String.valueOf(snooze) + " " + getString(R.string.minutes));
        snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> {
            String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants.PREF_SNOOZE_DEFAULT
                    : String.valueOf(newValue);
            snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes));
            prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply();
            return false;
        });
    }

    // NotificationServiceListener shortcut
    final Preference norificationServiceListenerPreference = findPreference(
            "settings_notification_service_listener");
    if (norificationServiceListenerPreference != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            getPreferenceScreen().removePreference(norificationServiceListenerPreference);
        }
    }

    // Changelog
    Preference changelog = findPreference("settings_changelog");
    if (changelog != null) {
        changelog.setOnPreferenceClickListener(arg0 -> {

            AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_changelog");

            new MaterialDialog.Builder(activity).customView(R.layout.activity_changelog, false)
                    .positiveText(R.string.ok).build().show();
            return false;
        });
        // Retrieval of installed app version to write it as summary
        PackageInfo pInfo;
        String versionString = "";
        try {
            pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionString = pInfo.versionName;
        } catch (NameNotFoundException e) {
            Log.e(Constants.TAG, "Error retrieving version", e);
        }
        changelog.setSummary(versionString);
    }

    // Settings reset
    Preference resetData = findPreference("reset_all_data");
    if (resetData != null) {
        resetData.setOnPreferenceClickListener(arg0 -> {

            new MaterialDialog.Builder(activity).content(R.string.reset_all_data_confirmation)
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            prefs.edit().clear().commit();
                            File db = getActivity().getDatabasePath(Constants.DATABASE_NAME);
                            StorageHelper.delete(getActivity(), db.getAbsolutePath());
                            File attachmentsDir = StorageHelper.getAttachmentDir(getActivity());
                            StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath());
                            File cacheDir = StorageHelper.getCacheDir(getActivity());
                            StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath());
                            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();

            return false;
        });
    }

    // Instructions
    Preference instructions = findPreference("settings_tour_show_again");
    if (instructions != null) {
        instructions.setOnPreferenceClickListener(arg0 -> {
            new MaterialDialog.Builder(getActivity())
                    .content(getString(R.string.settings_tour_show_again_summary) + "?")
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog materialDialog) {

                            AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING,
                                    "settings_tour_show_again");

                            prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).commit();
                            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();
            return false;
        });
    }

    // Donations
    //        Preference donation = findPreference("settings_donation");
    //        if (donation != null) {
    //            donation.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //                @Override
    //                public boolean onPreferenceClick(Preference preference) {
    //                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    //
    //                    ArrayList<ImageAndTextItem> options = new ArrayList<ImageAndTextItem>();
    //                    options.add(new ImageAndTextItem(R.drawable.ic_paypal, getString(R.string.paypal)));
    //                    options.add(new ImageAndTextItem(R.drawable.ic_bitcoin, getString(R.string.bitcoin)));
    //
    //                    alertDialogBuilder
    //                            .setAdapter(new ImageAndTextAdapter(getActivity(), options),
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog, int which) {
    //                                            switch (which) {
    //                                                case 0:
    //                                                    Intent intentPaypal = new Intent(Intent.ACTION_VIEW);
    //                                                    intentPaypal.setData(Uri.parse(getString(R.string.paypal_url)));
    //                                                    startActivity(intentPaypal);
    //                                                    break;
    //                                                case 1:
    //                                                    Intent intentBitcoin = new Intent(Intent.ACTION_VIEW);
    //                                                    intentBitcoin.setData(Uri.parse(getString(R.string.bitcoin_url)));
    //                                                    startActivity(intentBitcoin);
    //                                                    break;
    //                                            }
    //                                        }
    //                                    });
    //
    //
    //                    // create alert dialog
    //                    AlertDialog alertDialog = alertDialogBuilder.create();
    //                    // show it
    //                    alertDialog.show();
    //                    return false;
    //                }
    //            });
    //        }
}

From source file:com.dycody.android.idealnote.SettingsFragment.java

@SuppressWarnings("deprecation")
@Override//from   w  ww .j  a  v a 2 s  .c o  m
public void onResume() {
    super.onResume();

    // Export notes
    Preference export = findPreference("settings_export_data");
    if (export != null) {
        export.setOnPreferenceClickListener(arg0 -> {

            // Inflate layout
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.dialog_backup_layout, null);

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    () -> export(v));

            return false;
        });
    }

    // Import notes
    Preference importData = findPreference("settings_import_data");
    if (importData != null) {
        importData.setOnPreferenceClickListener(arg0 -> {
            importNotes();
            return false;
        });
    }

    // Import notes from Springpad export zip file
    Preference importFromSpringpad = findPreference("settings_import_from_springpad");
    if (importFromSpringpad != null) {
        importFromSpringpad.setOnPreferenceClickListener(arg0 -> {
            Intent intent;
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("application/zip");
            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            startActivityForResult(intent, SPRINGPAD_IMPORT);
            return false;
        });
    }

    //      Preference syncWithDrive = findPreference("settings_backup_drive");
    //      importFromSpringpad.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //         @Override
    //         public boolean onPreferenceClick(Preference arg0) {
    //            Intent intent;
    //            intent = new Intent(Intent.ACTION_GET_CONTENT);
    //            intent.addCategory(Intent.CATEGORY_OPENABLE);
    //            intent.setType("application/zip");
    //            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
    //               Crouton.makeText(getActivity(), R.string.feature_not_available_on_this_device,
    // ONStyle.ALERT).show();
    //               return false;
    //            }
    //            startActivityForResult(intent, SPRINGPAD_IMPORT);
    //            return false;
    //         }
    //      });

    // Swiping action
    final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash");
    if (swipeToTrash != null) {
        if (prefs.getBoolean("settings_swipe_to_trash", false)) {
            swipeToTrash.setChecked(true);
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
        } else {
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            swipeToTrash.setChecked(false);
        }
        swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((Boolean) newValue) {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
            } else {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            }
            swipeToTrash.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show uncategorized notes in menu
    final SwitchPreference showUncategorized = (SwitchPreference) findPreference(
            Constants.PREF_SHOW_UNCATEGORIZED);
    if (showUncategorized != null) {
        showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> {
            showUncategorized.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show Automatically adds location to new notes
    final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION);
    if (autoLocation != null) {
        autoLocation.setOnPreferenceChangeListener((preference, newValue) -> {
            autoLocation.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Maximum video attachment size
    final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size");
    if (maxVideoSize != null) {
        String maxVideoSizeValue = prefs.getString("settings_max_video_size", getString(R.string.not_set));
        maxVideoSize.setSummary(
                getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(maxVideoSizeValue));
        maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> {
            maxVideoSize.setSummary(
                    getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(newValue));
            prefs.edit().putString("settings_max_video_size", newValue.toString()).commit();
            return false;
        });
    }

    // Set notes' protection password
    Preference password = findPreference("settings_password");
    if (password != null) {
        password.setOnPreferenceClickListener(preference -> {
            Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class);
            startActivity(passwordIntent);
            return false;
        });
    }

    // Use password to grant application access
    final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access");
    if (passwordAccess != null) {
        if (prefs.getString(Constants.PREF_PASSWORD, null) == null) {
            passwordAccess.setEnabled(false);
            passwordAccess.setChecked(false);
        } else {
            passwordAccess.setEnabled(true);
        }
        passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> {
            PasswordHelper.requestPassword(getActivity(), passwordConfirmed -> {
                if (passwordConfirmed) {
                    passwordAccess.setChecked((Boolean) newValue);
                }
            });
            return false;
        });
    }

    // Languages
    ListPreference lang = (ListPreference) findPreference("settings_language");
    if (lang != null) {
        String languageName = getResources().getConfiguration().locale.getDisplayName();
        lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale)
                + languageName.substring(1, languageName.length()));
        lang.setOnPreferenceChangeListener((preference, value) -> {
            IdealNote.updateLanguage(getActivity(), value.toString());
            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
            return false;
        });
    }

    // Text size
    final ListPreference textSize = (ListPreference) findPreference("settings_text_size");
    if (textSize != null) {
        int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default"));
        String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex];
        textSize.setSummary(textSizeString);
        textSize.setOnPreferenceChangeListener((preference, newValue) -> {
            int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString());
            String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1];
            textSize.setSummary(checklistString);
            prefs.edit().putString("settings_text_size", newValue.toString()).commit();
            textSize.setValueIndex(textSizeIndex1);
            return false;
        });
    }

    // Application's colors
    final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app");
    if (colorsApp != null) {
        int colorsAppIndex = colorsApp
                .findIndexOfValue(prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex];
        colorsApp.setSummary(colorsAppString);
        colorsApp.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString());
            String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1];
            colorsApp.setSummary(colorsAppString1);
            prefs.edit().putString("settings_colors_app", newValue.toString()).commit();
            colorsApp.setValueIndex(colorsAppIndex1);
            return false;
        });
    }

    // Checklists
    final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior");
    if (checklist != null) {
        int checklistIndex = checklist
                .findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0"));
        String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex];
        checklist.setSummary(checklistString);
        checklist.setOnPreferenceChangeListener((preference, newValue) -> {
            int checklistIndex1 = checklist.findIndexOfValue(newValue.toString());
            String checklistString1 = getResources()
                    .getStringArray(R.array.checked_items_behavior)[checklistIndex1];
            checklist.setSummary(checklistString1);
            prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).commit();
            checklist.setValueIndex(checklistIndex1);
            return false;
        });
    }

    // Widget's colors
    final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget");
    if (colorsWidget != null) {
        int colorsWidgetIndex = colorsWidget
                .findIndexOfValue(prefs.getString("settings_colors_widget", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex];
        colorsWidget.setSummary(colorsWidgetString);
        colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString());
            String colorsWidgetString1 = getResources()
                    .getStringArray(R.array.colors_widget)[colorsWidgetIndex1];
            colorsWidget.setSummary(colorsWidgetString1);
            prefs.edit().putString("settings_colors_widget", newValue.toString()).commit();
            colorsWidget.setValueIndex(colorsWidgetIndex1);
            return false;
        });
    }

    // Notification snooze delay
    final EditTextPreference snoozeDelay = (EditTextPreference) findPreference(
            "settings_notification_snooze_delay");
    if (snoozeDelay != null) {
        String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT);
        snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze;
        snoozeDelay.setSummary(String.valueOf(snooze) + " " + getString(R.string.minutes));
        snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> {
            String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants.PREF_SNOOZE_DEFAULT
                    : String.valueOf(newValue);
            snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes));
            prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply();
            return false;
        });
    }

    // NotificationServiceListener shortcut
    final Preference norificationServiceListenerPreference = findPreference(
            "settings_notification_service_listener");
    if (norificationServiceListenerPreference != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            getPreferenceScreen().removePreference(norificationServiceListenerPreference);
        }
    }

    // Changelog
    Preference changelog = findPreference("settings_changelog");
    if (changelog != null) {
        changelog.setOnPreferenceClickListener(arg0 -> {

            ((IdealNote) getActivity().getApplication()).getAnalyticsHelper()
                    .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_changelog");

            new MaterialDialog.Builder(activity).customView(R.layout.activity_changelog, false)
                    .positiveText(R.string.ok).build().show();
            return false;
        });
        // Retrieval of installed app version to write it as summary
        PackageInfo pInfo;
        String versionString = "";
        try {
            pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionString = pInfo.versionName + getString(R.string.version_postfix);
        } catch (NameNotFoundException e) {
            Log.e(Constants.TAG, "Error retrieving version", e);
        }
        changelog.setSummary(versionString);
    }

    // Settings reset
    Preference resetData = findPreference("reset_all_data");
    if (resetData != null) {
        resetData.setOnPreferenceClickListener(arg0 -> {

            new MaterialDialog.Builder(activity).content(R.string.reset_all_data_confirmation)
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            prefs.edit().clear().commit();
                            File db = getActivity().getDatabasePath(Constants.DATABASE_NAME);
                            StorageHelper.delete(getActivity(), db.getAbsolutePath());
                            File attachmentsDir = StorageHelper.getAttachmentDir(getActivity());
                            StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath());
                            File cacheDir = StorageHelper.getCacheDir(getActivity());
                            StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath());
                            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();

            return false;
        });
    }

    // Instructions
    Preference instructions = findPreference("settings_tour_show_again");
    if (instructions != null) {
        instructions.setOnPreferenceClickListener(arg0 -> {
            new MaterialDialog.Builder(getActivity())
                    .content(getString(R.string.settings_tour_show_again_summary) + "?")
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog materialDialog) {

                            ((IdealNote) getActivity().getApplication()).getAnalyticsHelper()
                                    .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_tour_show_again");

                            prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).commit();
                            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();
            return false;
        });
    }

    // Donations
    //        Preference donation = findPreference("settings_donation");
    //        if (donation != null) {
    //            donation.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //                @Override
    //                public boolean onPreferenceClick(Preference preference) {
    //                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    //
    //                    ArrayList<ImageAndTextItem> options = new ArrayList<ImageAndTextItem>();
    //                    options.add(new ImageAndTextItem(R.drawable.ic_paypal, getString(R.string.paypal)));
    //                    options.add(new ImageAndTextItem(R.drawable.ic_bitcoin, getString(R.string.bitcoin)));
    //
    //                    alertDialogBuilder
    //                            .setAdapter(new ImageAndTextAdapter(getActivity(), options),
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog, int which) {
    //                                            switch (which) {
    //                                                case 0:
    //                                                    Intent intentPaypal = new Intent(Intent.ACTION_VIEW);
    //                                                    intentPaypal.setData(Uri.parse(getString(R.string.paypal_url)));
    //                                                    startActivity(intentPaypal);
    //                                                    break;
    //                                                case 1:
    //                                                    Intent intentBitcoin = new Intent(Intent.ACTION_VIEW);
    //                                                    intentBitcoin.setData(Uri.parse(getString(R.string.bitcoin_url)));
    //                                                    startActivity(intentBitcoin);
    //                                                    break;
    //                                            }
    //                                        }
    //                                    });
    //
    //
    //                    // create alert dialog
    //                    AlertDialog alertDialog = alertDialogBuilder.create();
    //                    // show it
    //                    alertDialog.show();
    //                    return false;
    //                }
    //            });
    //        }
}

From source file:com.cesarsk.say_it.ui.fragments.SettingsFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    // Use an activity context to get the rewarded video instance.
    mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getActivity());
    mRewardedVideoAd.setRewardedVideoAdListener(this);

    loadRewardedVideoAd();//  www  . jav a2 s  .c o m

    PackageInfo pInfo = null;
    try {
        pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    String version = pInfo.versionName;
    final Preference app_version = getPreferenceManager().findPreference("app_version");
    app_version.setSummary("Version: " + version + " (Click for Privacy Policy)");

    final Context context = getActivity();

    if (context instanceof Callback) {
        mCallback = (Callback) context;
    } else {
        throw new IllegalStateException("Owner must implement URLCallback interface");
    }

    // add listeners for non-default actions
    Preference preference = findPreference(KEY_1);
    preference.setOnPreferenceClickListener(this);

    Preference open_source_licenses = findPreference(KEY_2);
    open_source_licenses.setOnPreferenceClickListener(this);

    Preference rate_us = getPreferenceManager().findPreference("rate_us");
    rate_us.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            rateUs(getActivity());
            return false;
        }
    });

    Preference contact_us = getPreferenceManager().findPreference("contact_us");
    contact_us.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            shareToMail(emails, "[CONTACT US - SAY IT!]", getActivity());
            return false;
        }
    });

    Preference bug_report = getPreferenceManager().findPreference("bug_report");
    bug_report.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            shareToMail(emails, "[CONTACT US - SAY IT!]", getActivity());
            return false;
        }
    });

    Preference donate_ad = getPreferenceManager().findPreference("donation_ad");
    donate_ad.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            //Launch AD
            if (mRewardedVideoAd.isLoaded()) {
                mRewardedVideoAd.show();
            }
            return false;
        }
    });

    final Preference about_us = getPreferenceManager().findPreference("about_us");
    about_us.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(), "https://lucacesaranoblog.wordpress.com/2017/07/18/about-us/");
            return false;
        }
    });

    final Preference eula = getPreferenceManager().findPreference("eula");
    eula.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(),
                    "https://lucacesaranoblog.wordpress.com/2017/04/28/say-it-eula-agreement/");
            return false;
        }
    });

    /*final Preference github = getPreferenceManager().findPreference("github");
    github.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        Utility.openURL(getActivity(), "https://github.com/Cesarsk/Say_it");
        return false;
    }
    });*/

    final Preference other_apps = getPreferenceManager().findPreference("other_apps");
    other_apps.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(), "https://play.google.com/store/apps/developer?id=Cesarsk+Dev+Team");
            return false;
        }
    });

    final Preference voice_settings = getPreferenceManager().findPreference("tts_settings");
    voice_settings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent intent = new Intent();
            intent.setAction("com.android.settings.TTS_SETTINGS");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return false;
        }
    });

    // compute your public key and store it in base64EncodedPublicKey
    mHelper = new IabHelper(getActivity(), LCSecurity.base64EncodedPublicKey);
    mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        public void onIabSetupFinished(IabResult result) {
            if (!result.isSuccess()) {
                // Oh no, there was a problem.
                if (MainActivity.isLoggingEnabled)
                    Log.d("Say It!", "Problem setting up In-app Billing: " + result);
            }
            // Hooray, IAB is fully set up!
            if (MainActivity.isLoggingEnabled)
                Log.d("Say It!", "Hooray. IAB is fully set up!" + result);
        }
    });

    mIabPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        @Override
        public void onIabPurchaseFinished(IabResult result, Purchase info) {
            if (result.isFailure()) {
                Toast.makeText(getActivity(), "Purchase Failed! Perhaps have you already purchased the item?",
                        Toast.LENGTH_SHORT).show();
            } else if (info.getSku().equals(PlayActivity.no_ads_in_app)) {
                UtilitySharedPrefs.loadAdsStatus(getActivity());
                UtilitySharedPrefs.savePrefs(getActivity(), true, MainActivity.NO_ADS_STATUS_KEY);
            }
        }
    };

    mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            if (result.isFailure()) {
                if (MainActivity.isLoggingEnabled)
                    Toast.makeText(getActivity(), "Query Failed!", Toast.LENGTH_SHORT).show();
                return;
            }

            //Open Purchase Dialog
            try {
                mHelper.flagEndAsync();
                mHelper.launchPurchaseFlow(getActivity(), PlayActivity.no_ads_in_app, 64000,
                        mIabPurchaseFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                e.printStackTrace();
            }
        }
    };

    final Preference remove_ads = getPreferenceManager().findPreference("remove_ads");
    if (MainActivity.NO_ADS) {
        remove_ads.setEnabled(false);
        remove_ads.setSummary("Thank you for supporting us ?");
    } else {
        remove_ads.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                //helper to remove ads
                List<String> additionalSkuList = new ArrayList<>();
                additionalSkuList.add(PlayActivity.no_ads_in_app);
                try {
                    mHelper.flagEndAsync();
                    mHelper.queryInventoryAsync(true, additionalSkuList, mQueryFinishedListener);
                } catch (IabHelper.IabAsyncInProgressException e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
    }

    final Preference reset_tutorial = getPreferenceManager().findPreference("reset_showcase");
    reset_tutorial.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Random rand = new Random();
            int randomNum = rand.nextInt((10000 - 10) + 1) + 10; //(max - min) + 1 + min
            MainActivity.id_showcase_playactivity = "" + randomNum;
            Toast.makeText(getActivity(), "Tutorial has been reset", Toast.LENGTH_SHORT).show();
            //MainActivity.id_showcase_fragments = "" + randomNum2;
            //int randomNum2 = rand.nextInt((10000 - 10) + 1) + 10; //(max - min) + 1 + min //These two statements are commented because MaterialShowCase often crashes on fragments and while pressing the back button.
            return false;
        }
    });

    //setting an own Alert Dialog's title color
    final Spannable title = new SpannableString("Delete Recordings");
    title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0, title.length(), 0);
    final Spannable message = new SpannableString("Are you sure you want to delete all recordings?");
    message.setSpan(new ForegroundColorSpan(Color.GRAY), 0, message.length(), 0);

    final Preference delete_recordings = getPreferenceManager().findPreference("delete_recordings");
    delete_recordings.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            new AlertDialog.Builder(getActivity()).setTitle(title).setMessage(message)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Utility.delete_recordings(getActivity());
                            Toast.makeText(getActivity(), "Recordings deleted!", Toast.LENGTH_SHORT).show();
                        }
                    }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //do nothing
                        }
                    }).show();
            return true;
        }
    });

    final ListPreference button_vibration = (ListPreference) getPreferenceManager()
            .findPreference("button_vibration");
    button_vibration.setSummary(button_vibration.getEntry());
    final Spannable default_vibration_settings_title = new SpannableString("Vibration Settings");
    default_vibration_settings_title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0,
            default_vibration_settings_title.length(), 0);
    button_vibration.setDialogTitle(default_vibration_settings_title);

    button_vibration.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String new_value = newValue.toString();
            index_default_vibration = button_vibration.findIndexOfValue(new_value);
            CharSequence[] entries = button_vibration.getEntries();
            UtilitySharedPrefs.savePrefs(getActivity(), new_value, MainActivity.DEFAULT_VIBRATION_KEY);
            button_vibration
                    .setSummary(button_vibration.getEntries()[button_vibration.findIndexOfValue(new_value)]);
            Toast.makeText(getActivity(), String.valueOf(entries[index_default_vibration]), Toast.LENGTH_SHORT)
                    .show();
            UtilitySharedPrefs.loadSettingsPrefs(context);
            return true;
        }
    });

    final ListPreference default_accent = (ListPreference) getPreferenceManager()
            .findPreference("default_accent");
    default_accent.setSummary(default_accent.getEntry());
    final Spannable default_accent_title = new SpannableString("Default Accent");
    default_accent_title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0, default_accent_title.length(), 0);
    default_accent.setDialogTitle(default_accent_title);

    default_accent.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String new_value = newValue.toString();
            index_default_accent = default_accent.findIndexOfValue(new_value);
            CharSequence[] entries = default_accent.getEntries();

            UtilitySharedPrefs.savePrefs(getActivity(), new_value, MainActivity.DEFAULT_ACCENT_KEY);
            default_accent.setSummary(default_accent.getEntries()[default_accent.findIndexOfValue(new_value)]);
            //Toast.makeText(getActivity(), String.valueOf(entries[index_default_accent]), Toast.LENGTH_SHORT).show();
            UtilitySharedPrefs.loadSettingsPrefs(context);
            return true;
        }
    });

    final ListPreference theme_selector = (ListPreference) getPreferenceManager()
            .findPreference("theme_selector");
    final Spannable theme_selector_title = new SpannableString("Theme");
    theme_selector_title.setSpan(new ForegroundColorSpan(Color.DKGRAY), 0, theme_selector_title.length(), 0);
    theme_selector.setDialogTitle(theme_selector_title);

    theme_selector.setSummary(theme_selector.getEntry());

    theme_selector.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String new_value = newValue.toString();
            index_default_theme = theme_selector.findIndexOfValue(new_value);
            CharSequence[] entries = theme_selector.getEntries();
            UtilitySharedPrefs.savePrefs(getActivity(), new_value, MainActivity.DEFAULT_THEME_KEY);
            theme_selector.setSummary(theme_selector.getEntries()[theme_selector.findIndexOfValue(new_value)]);
            //Toast.makeText(getActivity(), String.valueOf(entries[index_default_theme]), Toast.LENGTH_SHORT).show();
            UtilitySharedPrefs.loadSettingsPrefs(context);
            Toast.makeText(getActivity(), "Done! Reboot to see changes.", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

    Preference acknowledgements = getPreferenceManager().findPreference("acknowledgements");
    acknowledgements.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            final Intent preference_intent = new Intent(getActivity(), FileTextActivity.class);
            Bundle args = new Bundle();
            args.putString(FileTextActivity.PREFERENCE, "acknowledgements");
            preference_intent.putExtras(args);
            startActivity(preference_intent,
                    ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
            return false;
        }
    });

    app_version.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Utility.openURL(getActivity(), "https://lucacesaranoblog.wordpress.com/2017/04/18/privacy-policy/");
            return false;
        }
    });
}