Example usage for android.preference CheckBoxPreference setChecked

List of usage examples for android.preference CheckBoxPreference setChecked

Introduction

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

Prototype

public void setChecked(boolean checked) 

Source Link

Document

Sets the checked state and saves it to the SharedPreferences .

Usage

From source file:fi.iki.murgo.irssinotifier.SettingsActivity.java

private void handleIcb() {
    CheckBoxPreference showIcbIconPreference = (CheckBoxPreference) findPreference("IcbEnabled");
    if (!IntentSniffer.isPackageAvailable(this, IrssiConnectbotLauncher.PACKAGE_IRSSICONNECTBOT)) {
        PreferenceCategory icbCategory = (PreferenceCategory) findPreference("IcbCategory");
        icbCategory.setEnabled(false);/*from   w w  w  .j  ava2  s  . co  m*/

        showIcbIconPreference.setChecked(false);
        showIcbIconPreference.setSummary("Install Irssi ConnectBot to show it in the action bar");
    } else {
        showIcbIconPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                IrssiNotifierActivity.refreshIsNeeded();

                return true;
            }
        });

        Preference icbHostPref = findPreference("IcbHost");

        Preferences prefs = new Preferences(this);
        String hostName = prefs.getIcbHostName();

        String summary = "Select which Irssi ConnectBot host to open when pressing the ICB icon";
        if (hostName != null)
            summary += ". Currently selected host: " + hostName;
        icbHostPref.setSummary(summary);

        icbHostPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                Intent i = new Intent("android.intent.action.PICK");
                i.setClassName(IrssiConnectbotLauncher.PACKAGE_IRSSICONNECTBOT,
                        IrssiConnectbotLauncher.PACKAGE_IRSSICONNECTBOT + ".HostListActivity");
                startActivityForResult(i, ICB_HOST_REQUEST_CODE);
                return true;
            }
        });
    }
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == ACTION_OPEN_DOCUMENT_TREE && resultCode == Activity.RESULT_OK) {
        Uri treeUri = resultData.getData();
        String path = treeUri.getPath();

        final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
        if (!":".equals(path.substring(path.length() - 1)) || path.contains("primary")) {
            writeExternalStorage_pref.setChecked(false);
        } else {/*from   www  .  j  a v  a  2  s. c  om*/
            FsSettings.setExternalStorageUri(treeUri.toString());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getActivity().getContentResolver().takePersistableUriPermission(treeUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            writeExternalStorage_pref.setChecked(true);
        }
    }

}

From source file:org.adblockplus.android.Preferences.java

private void setAcceptableAdsEnabled(final boolean enabled) {
    final CheckBoxPreference acceptableAdsPreference = (CheckBoxPreference) findPreference(
            getString(R.string.pref_acceptableads));
    acceptableAdsPreference.setChecked(enabled);
    final AdblockPlus application = AdblockPlus.getApplication();
    application.setAcceptableAdsEnabled(enabled);
}

From source file:com.newtifry.android.SourceEditor.java

/**
 * Load this activity from the given source.
 * @param source/* ww  w  .  j av a 2s.c om*/
 */
public void loadFromSource(NewtifrySource source) {
    // Create a new preferences mapper with updated source data.
    this.preferenceMapper = new ORMPreferencesMapper();

    Preference titlePreference = this.findPreference("source_title");
    titlePreference.setSummary(source.getTitle());

    Preference sourceKey = this.findPreference("source_key");
    sourceKey.setSummary(source.getSourceKey());

    // Force update the server enabled preference.
    CheckBoxPreference serverEnabled = (CheckBoxPreference) this.findPreference("source_server_enable");
    serverEnabled.setChecked(source.getServerEnabled());

    this.toggleNotificationPreferences(source.getUseGlobalNotification());
}

From source file:com.notifry.android.SourceEditor.java

/**
 * Load this activity from the given source.
 * //from   w ww  .  j a  v  a  2s. c om
 * @param source
 */
public void loadFromSource(NotifrySource source) {
    // Create a new preferences mapper with updated source data.
    this.preferenceMapper = new ORMPreferencesMapper();

    Preference titlePreference = this.findPreference("source_title");
    titlePreference.setSummary(source.getTitle());

    Preference sourceKey = this.findPreference("source_key");
    sourceKey.setSummary(source.getSourceKey());

    // Force update the server enabled preference.
    CheckBoxPreference serverEnabled = (CheckBoxPreference) this.findPreference("source_server_enable");
    serverEnabled.setChecked(source.getServerEnabled());

    this.toggleNotificationPreferences(source.getUseGlobalNotification());
}

From source file:org.wordpress.android.ui.prefs.SettingsFragment.java

@Override
public void onResume() {
    super.onResume();
    getActivity().setTitle(R.string.settings);

    // the set of blogs may have changed while we were away
    updateSelfHostedBlogsPreferenceCategory();
    refreshWPComAuthCategory();//from  w w w.  j a va 2  s .c  o  m

    //update Passcode lock row if available
    if (AppLockManager.getInstance().isAppLockFeatureEnabled()) {
        CheckBoxPreference passcodeEnabledCheckBoxPreference = (CheckBoxPreference) findPreference(
                getResources().getString(R.string.pref_key_passlock));
        if (AppLockManager.getInstance().getCurrentAppLock().isPasswordLocked()) {
            passcodeEnabledCheckBoxPreference.setChecked(true);
        } else {
            passcodeEnabledCheckBoxPreference.setChecked(false);
        }
    }
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

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

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Resources resources = getResources();

    TwoStatePreference runningPref = findPref("running_switch");
    updateRunningState();//  www.  ja va  2s  .  c o  m
    runningPref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((Boolean) newValue) {
            startServer();
        } else {
            stopServer();
        }
        return true;
    });

    PreferenceScreen prefScreen = findPref("preference_screen");
    Preference marketVersionPref = findPref("market_version");
    marketVersionPref.setOnPreferenceClickListener(preference -> {
        // start the market at our application
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=be.ppareit.swiftp"));
        try {
            // this can fail if there is no market installed
            startActivity(intent);
        } catch (Exception e) {
            Cat.e("Failed to launch the market.");
            e.printStackTrace();
        }
        return false;
    });
    if (!App.isFreeVersion()) {
        prefScreen.removePreference(marketVersionPref);
    }

    updateLoginInfo();

    EditTextPreference usernamePref = findPref("username");
    usernamePref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newUsername = (String) newValue;
        if (preference.getSummary().equals(newUsername))
            return false;
        if (!newUsername.matches("[a-zA-Z0-9]+")) {
            Toast.makeText(getActivity(), R.string.username_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        stopServer();
        return true;
    });

    mPassWordPref = findPref("password");
    mPassWordPref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });
    mAutoconnectListPref = findPref("autoconnect_preference");
    mAutoconnectListPref.setOnPopulateListener(pref -> {
        Cat.d("autoconnect populate listener");

        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        if (configs == null) {
            Cat.e("Unable to receive wifi configurations, bark at user and bail");
            Toast.makeText(getActivity(), R.string.autoconnect_error_enable_wifi_for_access_points,
                    Toast.LENGTH_LONG).show();
            return;
        }
        CharSequence[] ssids = new CharSequence[configs.size()];
        CharSequence[] niceSsids = new CharSequence[configs.size()];
        for (int i = 0; i < configs.size(); ++i) {
            ssids[i] = configs.get(i).SSID;
            String ssid = configs.get(i).SSID;
            if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
            niceSsids[i] = ssid;
        }
        pref.setEntries(niceSsids);
        pref.setEntryValues(ssids);
    });
    mAutoconnectListPref.setOnPreferenceClickListener(preference -> {
        Cat.d("Clicked");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    new AlertDialog.Builder(getContext()).setTitle(R.string.request_coarse_location_dlg_title)
                            .setMessage(R.string.request_coarse_location_dlg_message)
                            .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                                requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                                        ACCESS_COARSE_LOCATION_REQUEST_CODE);
                            }).setOnCancelListener(dialog -> {
                                mAutoconnectListPref.getDialog().cancel();
                            }).create().show();
                } else {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                            ACCESS_COARSE_LOCATION_REQUEST_CODE);
                }
            }
        }
        return false;
    });

    EditTextPreference portnum_pref = findPref("portNum");
    portnum_pref.setSummary(sp.getString("portNum", resources.getString(R.string.portnumber_default)));
    portnum_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newPortnumString = (String) newValue;
        if (preference.getSummary().equals(newPortnumString))
            return false;
        int portnum = 0;
        try {
            portnum = Integer.parseInt(newPortnumString);
        } catch (Exception e) {
            Cat.d("Error parsing port number! Moving on...");
        }
        if (portnum <= 0 || 65535 < portnum) {
            Toast.makeText(getActivity(), R.string.port_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        preference.setSummary(newPortnumString);
        stopServer();
        return true;
    });

    Preference chroot_pref = findPref("chrootDir");
    chroot_pref.setSummary(FsSettings.getChrootDirAsString());
    chroot_pref.setOnPreferenceClickListener(preference -> {
        AlertDialog folderPicker = new FolderPickerDialogBuilder(getActivity(), FsSettings.getChrootDir())
                .setSelectedButton(R.string.select, path -> {
                    if (preference.getSummary().equals(path))
                        return;
                    if (!FsSettings.setChrootDir(path))
                        return;
                    // TODO: this is a hotfix, create correct resources, improve UI/UX
                    final File root = new File(path);
                    if (!root.canRead()) {
                        Toast.makeText(getActivity(), "Notice that we can't read/write in this folder.",
                                Toast.LENGTH_LONG).show();
                    } else if (!root.canWrite()) {
                        Toast.makeText(getActivity(),
                                "Notice that we can't write in this folder, reading will work. Writing in sub folders might work.",
                                Toast.LENGTH_LONG).show();
                    }

                    preference.setSummary(path);
                    stopServer();
                }).setNegativeButton(R.string.cancel, null).create();
        folderPicker.show();
        return true;
    });

    final CheckBoxPreference wakelock_pref = findPref("stayAwake");
    wakelock_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });

    final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
    String externalStorageUri = FsSettings.getExternalStorageUri();
    if (externalStorageUri == null) {
        writeExternalStorage_pref.setChecked(false);
    }
    writeExternalStorage_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((boolean) newValue) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, ACTION_OPEN_DOCUMENT_TREE);
            return false;
        } else {
            FsSettings.setExternalStorageUri(null);
            return true;
        }
    });

    ListPreference theme = findPref("theme");
    theme.setSummary(theme.getEntry());
    theme.setOnPreferenceChangeListener((preference, newValue) -> {
        theme.setSummary(theme.getEntry());
        getActivity().recreate();
        return true;
    });

    Preference help = findPref("help");
    help.setOnPreferenceClickListener(preference -> {
        Cat.v("On preference help clicked");
        Context context = getActivity();
        AlertDialog ad = new AlertDialog.Builder(context).setTitle(R.string.help_dlg_title)
                .setMessage(R.string.help_dlg_message).setPositiveButton(android.R.string.ok, null).create();
        ad.show();
        Linkify.addLinks((TextView) ad.findViewById(android.R.id.message), Linkify.ALL);
        return true;
    });

    Preference about = findPref("about");
    about.setOnPreferenceClickListener(preference -> {
        startActivity(new Intent(getActivity(), AboutActivity.class));
        return true;
    });

}

From source file:nz.Intelx.DroidNetLogin.DroidNetLoginActivity.java

@Override
public boolean onPreferenceChange(Preference pref, Object newValue) {

    //match summary for Login list preference to selected preference

    if (pref.getKey().equals("login_preference")) {
        ListPreference login_preference = (ListPreference) pref;
        login_preference.setValue((String) newValue);
        CharSequence Login_Summary = login_preference.getEntry();
        login_preference.setSummary(Login_Summary);
    }/*from w ww  . jav  a  2s.  c o m*/
    if (pref.getKey().equals("debug_preference")) {
        CheckBoxPreference debug_preference = (CheckBoxPreference) pref;
        debug_preference.setChecked((Boolean) newValue);
    }
    if (pref.getKey().equals("proxy_preference")) {
        CheckBoxPreference proxy_preference = (CheckBoxPreference) pref;
        proxy_preference.setChecked((Boolean) newValue);
    }
    updatePreference(pref.getSharedPreferences());
    return true;
}

From source file:de.Maxr1998.xposed.maxlock.ui.settings.SettingsFragment.java

private void setupPro() {
    String version;/*from w  w  w . j  a v  a  2 s.  c o m*/
    try {
        version = " v" + getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(),
                0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        version = "Error getting app version";
        e.printStackTrace();
    }

    CheckBoxPreference ep = (CheckBoxPreference) findPreference(Common.ENABLE_PRO);
    String appName;
    if (BillingHelper.donated(getActivity().getApplicationContext(), getBp())) {
        appName = getString(R.string.app_name_pro);
        PREFS.edit().putBoolean(Common.ENABLE_PRO, true).apply();
        ep.setEnabled(false);
        ep.setChecked(true);
    } else {
        if (PREFS.getBoolean(Common.ENABLE_PRO, false))
            appName = getString(R.string.app_name_pseudo_pro);
        else
            appName = getString(R.string.app_name);
    }
    if (Util.isDevMode()) {
        appName = getString(R.string.app_name) + " Indev";
    }
    getActivity().setTitle(appName);

}

From source file:com.ichi2.anki.PreferenceContext.java

/**
 * Code which is run when a SharedPreference change has been detected
 * @param prefs instance of SharedPreferences
 * @param key key in prefs which is being updated
 * @param listener PreferenceActivity of PreferenceFragment which is hosting the preference
 *//*from w  w  w.  ja  v a2  s.co m*/
private void updatePreference(SharedPreferences prefs, String key, PreferenceContext listener) {
    try {
        PreferenceScreen screen = listener.getPreferenceScreen();
        Preference pref = screen.findPreference(key);
        // Handle special cases
        switch (key) {
        case "timeoutAnswer": {
            CheckBoxPreference keepScreenOn = (CheckBoxPreference) screen.findPreference("keepScreenOn");
            keepScreenOn.setChecked(((CheckBoxPreference) pref).isChecked());
            break;
        }
        case LANGUAGE:
            closePreferences();
            break;
        case "convertFenText":
            if (((CheckBoxPreference) pref).isChecked()) {
                ChessFilter.install(Hooks.getInstance(getApplicationContext()));
            } else {
                ChessFilter.uninstall(Hooks.getInstance(getApplicationContext()));
            }
            break;
        case "fixHebrewText":
            if (((CheckBoxPreference) pref).isChecked()) {
                HebrewFixFilter.install(Hooks.getInstance(getApplicationContext()));
                showDialog(DIALOG_HEBREW_FONT);
            } else {
                HebrewFixFilter.uninstall(Hooks.getInstance(getApplicationContext()));
            }
            break;
        case "showProgress":
            getCol().getConf().put("dueCounts", ((CheckBoxPreference) pref).isChecked());
            getCol().setMod();
            break;
        case "showEstimates":
            getCol().getConf().put("estTimes", ((CheckBoxPreference) pref).isChecked());
            getCol().setMod();
            break;
        case "newSpread":
            getCol().getConf().put("newSpread", Integer.parseInt(((ListPreference) pref).getValue()));
            getCol().setMod();
            break;
        case "timeLimit":
            getCol().getConf().put("timeLim", ((NumberRangePreference) pref).getValue() * 60);
            getCol().setMod();
            break;
        case "learnCutoff":
            getCol().getConf().put("collapseTime", ((NumberRangePreference) pref).getValue() * 60);
            getCol().setMod();
            break;
        case "useCurrent":
            getCol().getConf().put("addToCur", ((ListPreference) pref).getValue().equals("0"));
            getCol().setMod();
            break;
        case "dayOffset": {
            int hours = ((SeekBarPreference) pref).getValue();
            Timestamp crtTime = new Timestamp(getCol().getCrt() * 1000);
            Calendar date = GregorianCalendar.getInstance();
            date.setTimeInMillis(crtTime.getTime());
            date.set(Calendar.HOUR_OF_DAY, hours);
            getCol().setCrt(date.getTimeInMillis() / 1000);
            getCol().setMod();
            break;
        }
        case "minimumCardsDueForNotification": {
            ListPreference listpref = (ListPreference) screen.findPreference("minimumCardsDueForNotification");
            if (listpref != null) {
                updateNotificationPreference(listpref);
            }
            break;
        }
        case "reportErrorMode": {
            String value = prefs.getString("reportErrorMode", "");
            AnkiDroidApp.getInstance().setAcraReportingMode(value);
            break;
        }
        case "syncAccount": {
            SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
            String username = preferences.getString("username", "");
            Preference syncAccount = screen.findPreference("syncAccount");
            if (syncAccount != null) {
                if (TextUtils.isEmpty(username)) {
                    syncAccount.setSummary(R.string.sync_account_summ_logged_out);
                } else {
                    syncAccount.setSummary(getString(R.string.sync_account_summ_logged_in, username));
                }
            }
            break;
        }
        case "providerEnabled": {
            ComponentName providerName = new ComponentName(this, "com.ichi2.anki.provider.CardContentProvider");
            PackageManager pm = getPackageManager();
            int state;
            if (((CheckBoxPreference) pref).isChecked()) {
                state = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
                Timber.i("AnkiDroid ContentProvider enabled by user");
            } else {
                state = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
                Timber.i("AnkiDroid ContentProvider disabled by user");
            }
            pm.setComponentEnabledSetting(providerName, state, PackageManager.DONT_KILL_APP);
            break;
        }
        }
        // Update the summary text to reflect new value
        updateSummary(pref);
    } catch (BadTokenException e) {
        Timber.e(e, "Preferences: BadTokenException on showDialog");
    } catch (NumberFormatException | JSONException e) {
        throw new RuntimeException();
    }
}