Example usage for android.preference SwitchPreference setChecked

List of usage examples for android.preference SwitchPreference setChecked

Introduction

In this page you can find the example usage for android.preference SwitchPreference setChecked.

Prototype

public void setChecked(boolean checked) 

Source Link

Document

Sets the checked state and saves it to the SharedPreferences .

Usage

From source file:Main.java

static void addSwitchPreferenceBasedOnCheckBoxPreference(final CheckBoxPreference checkBox,
        final PreferenceGroup group) {
    final SwitchPreference switchPref = new SwitchPreference(checkBox.getContext());
    switchPref.setTitle(checkBox.getTitle());
    switchPref.setKey(checkBox.getKey());
    switchPref.setOrder(checkBox.getOrder());
    switchPref.setPersistent(checkBox.isPersistent());
    switchPref.setEnabled(checkBox.isEnabled());
    switchPref.setChecked(checkBox.isChecked());
    switchPref.setSummary(checkBox.getSummary());
    switchPref.setSummaryOn(checkBox.getSummaryOn());
    switchPref.setSummaryOff(checkBox.getSummaryOff());
    switchPref.setSwitchTextOn(EMPTY_TEXT);
    switchPref.setSwitchTextOff(EMPTY_TEXT);
    group.addPreference(switchPref);/*from   w ww .  j  a v  a 2  s . c  o  m*/
    switchPref.setDependency(checkBox.getDependency());
}

From source file:com.wolkabout.hexiwear.fragment.HexiwearSettingsFragment.java

@AfterPreferences
void initPrefs() {
    SettingsActivity settingsActivity = (SettingsActivity) getActivity();
    device = settingsActivity.device;//w w w . ja  va  2s.  c  o  m
    displayPreferences = hexiwearDevices.getDisplayPreferences(device.getDeviceAddress());

    for (Map.Entry<String, Boolean> entry : displayPreferences.entrySet()) {
        Log.d(TAG, "Key: " + entry.getKey() + " value " + entry.getValue());
        final SwitchPreference displayPref = (SwitchPreference) findPreference(entry.getKey());
        if (displayPref != null) {
            displayPref.setChecked(entry.getValue());
            displayPref.setOnPreferenceChangeListener(this);
        }
    }

    final String interval = String.format(getActivity().getString(R.string.preferences_publish_interval_value),
            hexiwearDevices.getPublishInterval(device));
    publishInterval.setSummary(interval);
    publishInterval.setOnPreferenceChangeListener(this);
    keepAlive.setChecked(hexiwearDevices.shouldKeepAlive(device));
    keepAlive.setOnPreferenceChangeListener(this);
    publish.setChecked(hexiwearDevices.shouldTransmit(device));
    publish.setOnPreferenceChangeListener(this);
    manufacturerInfo.setSummary(settingsActivity.manufacturerInfo.manufacturer);
    fwVersion.setSummary(settingsActivity.manufacturerInfo.firmwareRevision);

    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

From source file:org.deviceconnect.android.uiapp.fragment.profile.ConnectProfileFragment.java

/**
 * SwitchPreference????.//from ww  w.  j  a  v  a 2s  .  c o m
 * @param key 
 */
private void toggleCheckedPreference(final String key) {
    SwitchPreference pref = (SwitchPreference) findPreference(key);
    pref.setChecked(!pref.isChecked());
}

From source file:ota.otaupdates.Settings.java

@Override
public void onCreate(Bundle savedInstanceState) {

    if (MainActivity.sharedPreferences.getBoolean("apptheme_light", false))
        setTheme(R.style.AppTheme_Light);
    else/*from  w  w w .  java  2s.  c om*/
        setTheme(R.style.AppTheme_Dark);

    super.onCreate(savedInstanceState);

    addPreferencesFromResource(R.xml.preferences);

    SwitchPreference enable_auto_install = (SwitchPreference) findPreference("enable_auto_install");
    if (!Shell.SU.available()) {
        enable_auto_install.setEnabled(false);
        enable_auto_install.setChecked(false);
        enable_auto_install.setSummary(getString(R.string.auto_install_root_only));
    }

    final SwitchPreference setEnglish = (SwitchPreference) findPreference("force_english");
    setEnglish.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            AlertDialog.Builder builder = new AlertDialog.Builder(Settings.this);

            if (MainActivity.sharedPreferences.getBoolean("force_english", false))
                builder.setTitle(getString(R.string.force_english_window_title));
            else
                builder.setTitle(getString(R.string.force_default_window_title));

            builder.setMessage(getString(R.string.force_english_window_message));
            builder.setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });
            builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            AlertDialog alert = builder.create();
            alert.setCancelable(true);
            alert.show();
            return true;
        }
    });

    SwitchPreference apptheme_light = (SwitchPreference) findPreference("apptheme_light");
    apptheme_light.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            AlertDialog.Builder builder = new AlertDialog.Builder(Settings.this);
            if (MainActivity.sharedPreferences.getBoolean("apptheme_light", false))
                setTheme(R.style.AppTheme_Light);
            else
                setTheme(R.style.AppTheme_Dark);
            builder.setMessage(getString(R.string.switch_apptheme_light_window_message));
            builder.setPositiveButton(getString(R.string.button_yes), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });
            builder.setNegativeButton(getString(R.string.button_no), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            AlertDialog alert = builder.create();
            alert.setCancelable(true);
            alert.show();
            return true;
        }
    });

    findPreference("clean_junk").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (Build.VERSION.SDK_INT >= 23 && !checkPermission()) {
                // If user hasn't allowed yet, request the permission.
                requestPermission();
            }
            final AlertDialog.Builder delete_dialog = new AlertDialog.Builder(Settings.this);
            delete_dialog.setMessage(R.string.clean_junk_dialog_summary);
            delete_dialog.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    File folder = new File(Utils.DL_PATH);
                    File fList[] = folder.listFiles();
                    if (fList != null) {
                        for (i = 0; i < fList.length; i++) {
                            String pes = String.valueOf(fList[i]);
                            if (pes.endsWith(".zip")) {
                                fList[i].delete();
                            }
                        }
                    }
                    Log.d(getString(R.string.app_name) + ": clean_junk", "Old files cleaned");
                    Toast.makeText(getApplicationContext(), R.string.clean_junk_toast, Toast.LENGTH_SHORT)
                            .show();
                }
            });
            delete_dialog.setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
            delete_dialog.show();
            return true;
        }
    });

    findPreference("devs").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            clickcount++;
            switch (clickcount) {
            case 8:
            case 12:
            case 16:
            case 20:
            case 24:
                Toast.makeText(getApplicationContext(), R.string.crash_soon, Toast.LENGTH_SHORT).show();
                break;
            case 28:
                Toast.makeText(getApplicationContext(), R.string.crash_soon_really, Toast.LENGTH_SHORT).show();
                final Timer timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                clickcount = 0;
                                Toast.makeText(getApplicationContext(), R.string.crash_soon_gaveup,
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                        timer.cancel();
                    }
                }, 4000, 1);
                break;
            case 35:
                throw new NullPointerException("Well, you pointed at something...");
            }
            return true;
        }
    });

}

From source file:fr.s13d.photobackup.preferences.PBPreferenceFragment.java

private void initPreferences() {
    ((PBActivity) getActivity()).setActionBar();

    // switch on if service is running
    final SwitchPreference switchPreference = (SwitchPreference) findPreference(
            PBConstants.PREF_SERVICE_RUNNING);
    switchPreference.setChecked(isPhotoBackupServiceRunning());

    // initiate preferences summaries
    setSummaries();//from w  w w .j  a v a 2  s  .c  om
}

From source file:fr.s13d.photobackup.preferences.PBPreferenceFragment.java

public void onTestFailure() {
    getActivity().runOnUiThread(new Runnable() {
        @Override//from  w w  w. jav a  2 s  .  com
        public void run() {
            final SwitchPreference switchPreference = (SwitchPreference) findPreference(
                    PBConstants.PREF_SERVICE_RUNNING);
            switchPreference.setChecked(false);
        }
    });
}

From source file:fr.s13d.photobackup.preferences.PBPreferenceFragment.java

private void startOrStopService(final SharedPreferences preferences) {
    boolean userDidStart = preferences.getBoolean(PBConstants.PREF_SERVICE_RUNNING, false);
    Log.i(LOG_TAG, "PREF_SERVICE_RUNNING = " + userDidStart);

    if (userDidStart) {
        if (validatePreferences()) {
            checkPermissions(PBConstants.PERM_ORIGIN_SERVICE);
        } else {/*www.  j  a v a 2 s .  co  m*/
            final SwitchPreference switchPreference = (SwitchPreference) findPreference(
                    PBConstants.PREF_SERVICE_RUNNING);
            switchPreference.setChecked(false);
        }
    } else if (isPhotoBackupServiceRunning() && currentService != null) {
        Log.i(LOG_TAG, "stop PhotoBackup service");
        getActivity().unbindService(serviceConnection);
        getActivity().invalidateOptionsMenu();
        isBoundToService = false;
        currentService.stopSelf();
        currentService = null;
        updatePreferences();
    }
}

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

@SuppressWarnings("deprecation")
@Override//from  ww w. j  a v a2 s. com
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 w  w .  j  a  v a2 s  .  c  om*/
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.mantz_it.rfanalyzer.SettingsFragment.java

/**
 * Will go through each preference element and initialize/update the summary according to its value.
 * @note this will also correct invalid user inputs on EdittextPreferences!
 *//*  w  ww .  j  av a  2s . co  m*/
public void updateSummaries() {
    // Source Type
    ListPreference listPref = (ListPreference) findPreference(getString(R.string.pref_sourceType));
    listPref.setSummary(getString(R.string.pref_sourceType_summ, listPref.getEntry()));

    // Direct Sampling
    listPref = (ListPreference) findPreference(getString(R.string.pref_rtlsdr_directSamp));
    listPref.setSummary(getString(R.string.pref_rtlsdr_directSamp_summ, listPref.getEntry()));

    // Frequency display
    listPref = (ListPreference) findPreference(getString(R.string.pref_surface_unit));
    listPref.setSummary(getString(R.string.pref_surface_unit_summ, listPref.getEntry()));

    // FileSource Frequency
    EditTextPreference editTextPref = (EditTextPreference) findPreference(
            getString(R.string.pref_filesource_frequency));
    if (editTextPref.getText().length() == 0)
        editTextPref.setText(getString(R.string.pref_filesource_frequency_default));
    editTextPref.setSummary(getString(R.string.pref_filesource_frequency_summ, editTextPref.getText()));

    // FileSource Sample Rate
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_filesource_sampleRate));
    if (editTextPref.getText().length() == 0)
        editTextPref.setText(getString(R.string.pref_filesource_sampleRate_default));
    editTextPref.setSummary(getString(R.string.pref_filesource_sampleRate_summ, editTextPref.getText()));

    // FileSource File
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_filesource_file));
    editTextPref.setSummary(getString(R.string.pref_filesource_file_summ, editTextPref.getText()));

    // FileSource Format
    listPref = (ListPreference) findPreference(getString(R.string.pref_filesource_format));
    listPref.setSummary(getString(R.string.pref_filesource_format_summ, listPref.getEntry()));

    // HackRF frequency shift
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_hackrf_frequencyOffset));
    if (editTextPref.getText().length() == 0)
        editTextPref.setText("0");
    editTextPref.setSummary(getString(R.string.pref_hackrf_frequencyOffset_summ, editTextPref.getText()));

    // RTL-SDR IP
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_rtlsdr_ip));
    editTextPref.setSummary(getString(R.string.pref_rtlsdr_ip_summ, editTextPref.getText()));

    // RTL-SDR Port
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_rtlsdr_port));
    editTextPref.setSummary(getString(R.string.pref_rtlsdr_port_summ, editTextPref.getText()));

    // RTL-SDR frequency correction
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_rtlsdr_frequencyCorrection));
    if (editTextPref.getText().length() == 0)
        editTextPref.setText(getString(R.string.pref_rtlsdr_frequencyCorrection_default));
    editTextPref.setSummary(getString(R.string.pref_rtlsdr_frequencyCorrection_summ, editTextPref.getText()));

    // RTL-SDR frequency shift
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_rtlsdr_frequencyOffset));
    if (editTextPref.getText().length() == 0)
        editTextPref.setText("0");
    editTextPref.setSummary(getString(R.string.pref_rtlsdr_frequencyOffset_summ, editTextPref.getText()));

    // FFT size
    listPref = (ListPreference) findPreference(getString(R.string.pref_fftSize));
    listPref.setSummary(getString(R.string.pref_fftSize_summ, listPref.getEntry()));

    // Color map type
    listPref = (ListPreference) findPreference(getString(R.string.pref_colorMapType));
    listPref.setSummary(getString(R.string.pref_colorMapType_summ, listPref.getEntry()));

    // FFT drawing type
    listPref = (ListPreference) findPreference(getString(R.string.pref_fftDrawingType));
    listPref.setSummary(getString(R.string.pref_fftDrawingType_summ, listPref.getEntry()));

    // Averaging
    listPref = (ListPreference) findPreference(getString(R.string.pref_averaging));
    listPref.setSummary(getString(R.string.pref_averaging_summ, listPref.getEntry()));

    // Screen Orientation
    listPref = (ListPreference) findPreference(getString(R.string.pref_screenOrientation));
    listPref.setSummary(getString(R.string.pref_screenOrientation_summ, listPref.getEntry()));

    // Spectrum Waterfall Ratio
    listPref = (ListPreference) findPreference(getString(R.string.pref_spectrumWaterfallRatio));
    listPref.setSummary(getString(R.string.pref_spectrumWaterfallRatio_summ, listPref.getEntry()));

    // Font Size
    listPref = (ListPreference) findPreference(getString(R.string.pref_fontSize));
    listPref.setSummary(getString(R.string.pref_fontSize_summ, listPref.getEntry()));

    // Frame Rate
    SwitchPreference switchPref = (SwitchPreference) findPreference(getString(R.string.pref_dynamicFrameRate));
    listPref = (ListPreference) findPreference(getString(R.string.pref_frameRate));
    if (switchPref.isChecked())
        listPref.setSummary(getString(R.string.pref_frameRate_summ, "auto"));
    else
        listPref.setSummary(getString(R.string.pref_frameRate_summ, listPref.getEntry()));

    // Logfile
    editTextPref = (EditTextPreference) findPreference(getString(R.string.pref_logfile));
    editTextPref.setSummary(getString(R.string.pref_logfile_summ, editTextPref.getText()));

    // Shared preferences updated in e.g. the onRequestPermissionResult() method are
    // not automatically updated in the preference fragment gui. do it manually:
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
    switchPref = (SwitchPreference) findPreference(getString(R.string.pref_logging));
    switchPref.setChecked(preferences.getBoolean(getString(R.string.pref_logging), false));
}