Java Code Examples for android.preference.ListPreference#setValueIndex()

The following examples show how to use android.preference.ListPreference#setValueIndex() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SettingsActivity.java    From M365-Power with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref_general);
    setHasOptionsMenu(true);
    ListPreference speedListPreference = (ListPreference) findPreference("min_speed");
    ListPreference effListPreference = (ListPreference) findPreference("default_efficiency");


    //Statistics.setDefault_efficiency(Integer.valueOf(String.valueOf(effListPreference.getValue())));
    //Statistics.setMin_speed(Integer.valueOf(String.valueOf(speedListPreference.getValue())));

    speedListPreference.setValueIndex(3);
    speedListPreference.setValue("4");
    effListPreference.setValueIndex(7);
    effListPreference.setValue("600");
    // Bind the summaries of EditText/List/Dialog/Ringtone preferences
    // to their values. When their values change, their summaries are
    // updated to reflect the new value, per the Android Design
    // guidelines.
    bindPreferenceSummaryToValue(findPreference("min_speed"));
    bindPreferenceSummaryToValue(findPreference("default_efficiency"));
}
 
Example 2
Source File: SettingsActivity.java    From al-muazzin with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Activity activity = getActivity();
    sLocaleManager = LocaleManager.getInstance(activity, false);

    addPreferencesFromResource(R.xml.settings);
    PreferenceScreen root = getPreferenceScreen();
    // System time zone
    Preference timezonePref = root.findPreference("key_time_zone");
    timezonePref.setSummary(getGmtOffSet(activity));

    // Language settings
    ListPreference languagePref = (ListPreference) root.findPreference("key_locale");
    languagePref.setEntryValues(LocaleManager.LOCALES);
    languagePref.setValueIndex(sLocaleManager.getLanguageIndex());
    languagePref.setSummary(languagePref.getEntry());
    languagePref.setOnPreferenceChangeListener(this);
}
 
Example 3
Source File: SettingsFragment.java    From 600SeriesAndroidUploader with MIT License 6 votes vote down vote up
/**
 * set lowBatPollInterval to normal poll interval at least
 * and adapt the selectable values
 *
 * @param pollIntervalPref
 * @param lowBatPollIntervalPref
 */
private void setMinBatPollIntervall(ListPreference pollIntervalPref, ListPreference lowBatPollIntervalPref) {
    final String currentValue = lowBatPollIntervalPref.getValue();
    final int pollIntervalPos = (pollIntervalPref.findIndexOfValue(pollIntervalPref.getValue()) >= 0?pollIntervalPref.findIndexOfValue(pollIntervalPref.getValue()):0),
            length = pollIntervalPref.getEntries().length;

    CharSequence[] entries = new String[length - pollIntervalPos],
            entryValues = new String[length - pollIntervalPos];

    // generate temp Entries and EntryValues
    for(int i = pollIntervalPos; i < length; i++) {
        entries[i - pollIntervalPos] = pollIntervalPref.getEntries()[i];
        entryValues[i - pollIntervalPos] = pollIntervalPref.getEntryValues()[i];
    }
    lowBatPollIntervalPref.setEntries(entries);
    lowBatPollIntervalPref.setEntryValues(entryValues);

    // and set the correct one
    if (lowBatPollIntervalPref.findIndexOfValue(currentValue) == -1) {
        lowBatPollIntervalPref.setValueIndex(0);
    }
}
 
Example 4
Source File: AccountPreferencesFragment.java    From Linphone4Android with GNU General Public License v3.0 6 votes vote down vote up
private void initializeTransportPreference(ListPreference pref) {
	List<CharSequence> entries = new ArrayList<CharSequence>();
	List<CharSequence> values = new ArrayList<CharSequence>();
	entries.add(getString(R.string.pref_transport_udp));
	values.add(getString(R.string.pref_transport_udp_key));
	entries.add(getString(R.string.pref_transport_tcp));
	values.add(getString(R.string.pref_transport_tcp_key));

	if (!getResources().getBoolean(R.bool.disable_all_security_features_for_markets)) {
		entries.add(getString(R.string.pref_transport_tls));
		values.add(getString(R.string.pref_transport_tls_key));
	}
	setListPreferenceValues(pref, entries, values);

	if (! isNewAccount) {
		pref.setSummary(mPrefs.getAccountTransportString(n));
		pref.setDefaultValue(mPrefs.getAccountTransportKey(n));
		pref.setValueIndex(entries.indexOf(mPrefs.getAccountTransportString(n)));
	} else {

		pref.setSummary(getString(R.string.pref_transport_udp));
		pref.setDefaultValue(getString(R.string.pref_transport_udp));
		pref.setValueIndex(entries.indexOf(getString(R.string.pref_transport_udp)));
	}
}
 
Example 5
Source File: SettingsActivity.java    From MuslimMateAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
    sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    locationInfo = ConfigPreferences.getLocationConfig(getActivity());
    //disable and enable praying notification related setting
    if (ConfigPreferences.getPrayingNotification(getActivity()) == false) {
        getPreferenceScreen().findPreference("silent").setEnabled(false);
        getPreferenceScreen().findPreference("vibration").setEnabled(false);
        getPreferenceScreen().findPreference("led").setEnabled(false);
    }

    //disable or enable silent related settings
    if(ConfigPreferences.getSilentMood(getActivity()) == false){
        getPreferenceScreen().findPreference("vibration").setEnabled(false);
    }

    if (locationInfo != null) {
        Log.i("DATA_SETTING" ,"locationInfo.dls : "+(locationInfo.dls > 0));
        CheckBoxPreference checked = (CheckBoxPreference) getPreferenceScreen().findPreference("day_light");
        checked.setChecked(locationInfo.dls > 0);
        ListPreference wayPref = (ListPreference) getPreferenceScreen().findPreference("calculations");
        Log.i("DATA_SETTING" ,"locationInfo.way : "+locationInfo.way);
        wayPref.setValueIndex(locationInfo.way);
        ListPreference mazhapPref = (ListPreference) getPreferenceScreen().findPreference("mazhab");
        mazhapPref.setValueIndex(locationInfo.mazhab);
        Log.i("DATA_SETTING" ,"locationInfo.mazhab : "+locationInfo.mazhab);
    }

    listPreference = (ListPreference) findPreference("language");
    String lang = ConfigPreferences.getApplicationLanguage(getActivity()).equalsIgnoreCase("en") ? "English" : "العربية";
    listPreference.setSummary(getString(R.string.language_summary)
            + "  (" + lang + ") ");

}
 
Example 6
Source File: SingleWebsitePreferences.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the location preference to indicate that the site has access to location (via X-Geo)
 * for searches that happen from the omnibox.
 * @param preference The Location preference to modify.
 */
private void updateLocationPreferenceForXGeo(Preference preference) {
    ListPreference listPreference = (ListPreference) preference;
    Resources res = getResources();
    listPreference.setEntries(new String[] {
            res.getString(R.string.website_settings_permissions_allow_dse),
            res.getString(ContentSettingsResources.getSiteSummary(ContentSetting.BLOCK)),
    });
    listPreference.setEntryValues(new String[] {
            ContentSetting.DEFAULT.toString(),
            ContentSetting.BLOCK.toString(),
    });
    listPreference.setValueIndex(0);
}
 
Example 7
Source File: SingleWebsitePreferences.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the location preference to indicate that the site has access to location (via X-Geo)
 * for searches that happen from the omnibox.
 * @param preference The Location preference to modify.
 */
private void updateLocationPreferenceForXGeo(Preference preference) {
    ListPreference listPreference = (ListPreference) preference;
    Resources res = getResources();
    listPreference.setEntries(new String[] {
            res.getString(R.string.website_settings_permissions_allow_dse),
            res.getString(ContentSettingsResources.getSiteSummary(ContentSetting.BLOCK)),
    });
    listPreference.setEntryValues(new String[] {
            ContentSetting.DEFAULT.toString(),
            ContentSetting.BLOCK.toString(),
    });
    listPreference.setValueIndex(0);
}
 
Example 8
Source File: MyPreferencesActivity.java    From EasyVPN-Free with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(final Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    DBHelper dbHelper = new DBHelper(getActivity().getApplicationContext());
    List<Server> countryList = dbHelper.getUniqueCountries();
    CharSequence entriesValues[] = new CharSequence[countryList.size()];
    CharSequence entries[] = new CharSequence[countryList.size()];

    for (int i = 0; i < countryList.size(); i++) {
        entriesValues[i] = countryList.get(i).getCountryLong();
        String localeCountryName = CountriesNames.getCountries().get(countryList.get(i).getCountryShort()) != null ?
                CountriesNames.getCountries().get(countryList.get(i).getCountryShort()) :
                countryList.get(i).getCountryLong();
        entries[i] = localeCountryName;
    }

    ListPreference listPreference = (ListPreference) findPreference("selectedCountry");
    if (entries.length == 0) {
        PreferenceCategory countryPriorityCategory = (PreferenceCategory) findPreference("countryPriorityCategory");
        getPreferenceScreen().removePreference(countryPriorityCategory);
    } else {
        listPreference.setEntries(entries);
        listPreference.setEntryValues(entriesValues);
        if (PropertiesService.getSelectedCountry() == null)
            listPreference.setValueIndex(0);
    }
}
 
Example 9
Source File: OthersPreferenceFragment.java    From SkyTube with GNU General Public License v3.0 5 votes vote down vote up
@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preference_others);

		// Default tab
		defaultTabPref = (ListPreference)findPreference(getString(R.string.pref_key_default_tab_name));
		Set<String> hiddenFragments = SkyTubeApp.getPreferenceManager().getStringSet(getString(R.string.pref_key_hide_tabs), new HashSet<>());
		String[] tabListValues = SkyTubeApp.getStringArray(R.array.tab_list_values);
		if(hiddenFragments.size() == 0) {
			defaultTabPref.setEntries(SkyTubeApp.getStringArray(R.array.tab_list));
			defaultTabPref.setEntryValues(tabListValues);
		} else {
			List<String> defaultTabEntries = new ArrayList<>();
			List<String> defaultTabEntryValues = new ArrayList<>();
			for(int i=0;i<SkyTubeApp.getStringArray(R.array.tab_list).length;i++) {
				if(!hiddenFragments.contains(tabListValues[i])) {
					defaultTabEntries.add(SkyTubeApp.getStringArray(R.array.tab_list)[i]);
					defaultTabEntryValues.add(tabListValues[i]);

				}
			}
			defaultTabPref.setEntries(defaultTabEntries.toArray(new CharSequence[defaultTabEntries.size()]));
			defaultTabPref.setEntryValues(defaultTabEntryValues.toArray(new CharSequence[defaultTabEntryValues.size()]));
		}
		if (defaultTabPref.getValue() == null) {
			defaultTabPref.setValueIndex(0);
		}
		defaultTabPref.setSummary(String.format(getString(R.string.pref_summary_default_tab), defaultTabPref.getEntry()));

		MultiSelectListPreference hiddenTabsPref = (MultiSelectListPreference)findPreference(getString(R.string.pref_key_hide_tabs));
		hiddenTabsPref.setEntryValues(tabListValues);

//		ListPreference feedNotificationPref = (ListPreference) findPreference(getString(R.string.pref_feed_notification_key));
//		if(feedNotificationPref.getValue() == null) {
//			feedNotificationPref.setValueIndex(0);
//		}
//		feedNotificationPref.setSummary(String.format(getString(R.string.pref_summary_feed_notification), feedNotificationPref.getEntry()));
	}
 
Example 10
Source File: NotificationsSettingsFragment.java    From FaceSlim with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // load the preferences from an XML resource
    addPreferencesFromResource(R.xml.notifications_preferences);

    context = MyApplication.getContextOfApplication();
    preferences = PreferenceManager.getDefaultSharedPreferences(context);

    // default value for interval_pref preference summary
    ListPreference lp = (ListPreference) findPreference("interval_pref");
    String temp1 = getString(R.string.interval_pref_description_new).replace("%s", "");
    String temp2 = lp.getSummary().toString();
    if (temp1.equals(temp2))
        lp.setValueIndex(4);

    // listener for changing preferences (works after the value change)
    prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            // service intent (start, stop)
            final Intent intent = new Intent(context, NotificationsService.class);

            switch (key) {
                case "interval_pref":
                    // restart the service after time interval change
                    if (prefs.getBoolean("notifications_activated", false) || prefs.getBoolean("message_notifications", false)) {
                        context.stopService(intent);
                        context.startService(intent);
                    }
                    break;
            }
        }
    };
}
 
Example 11
Source File: SingleWebsitePreferences.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the location preference to indicate that the site has access to location (via X-Geo)
 * for searches that happen from the omnibox.
 * @param preference The Location preference to modify.
 */
private void updateLocationPreferenceForXGeo(Preference preference) {
    ListPreference listPreference = (ListPreference) preference;
    Resources res = getResources();
    listPreference.setEntries(new String[] {
            res.getString(R.string.website_settings_permissions_allow_dse_address_bar),
            res.getString(ContentSettingsResources.getSiteSummary(ContentSetting.BLOCK)),
    });
    listPreference.setEntryValues(new String[] {
            ContentSetting.DEFAULT.toString(),
            ContentSetting.BLOCK.toString(),
    });
    listPreference.setValueIndex(0);
}
 
Example 12
Source File: SingleWebsitePreferences.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the location preference to indicate that the site has access to location (via X-Geo)
 * for searches that happen from the omnibox.
 * @param preference The Location preference to modify.
 */
private void updateLocationPreferenceForDSESetting(Preference preference) {
    ListPreference listPreference = (ListPreference) preference;
    Resources res = getResources();
    listPreference.setEntries(new String[] {
            res.getString(R.string.website_settings_permissions_allow_dse),
            res.getString(R.string.website_settings_permissions_block_dse),
    });
    listPreference.setValueIndex(
            WebsitePreferenceBridge.getDSEGeolocationSetting() ? 0 : 1);
}
 
Example 13
Source File: SuntimesSettingsActivity.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
private static void loadPref_timeFormat(final Activity context, final ListPreference timeformatPref)
{
    WidgetSettings.TimeFormatMode mode = WidgetSettings.loadTimeFormatModePref(context, 0);
    int index = timeformatPref.findIndexOfValue(mode.name());
    if (index < 0)
    {
        index = 0;
        WidgetSettings.TimeFormatMode mode0 = mode;
        mode = WidgetSettings.TimeFormatMode.values()[index];
        Log.w("loadPref", "timeFormat not found (" + mode0 + ") :: loading " + mode.name() + " instead..");
    }
    timeformatPref.setValueIndex(index);
    timeformatPref.setSummary(timeFormatPrefSummary(mode, context));
}
 
Example 14
Source File: WidgetActivity.java    From Torch with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
  // No need to go to fragments right now
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

mActivity = this;
      mContext = this.getApplicationContext();
      mPreferences = PreferenceManager.getDefaultSharedPreferences(this);

      addPreferencesFromResource(R.layout.activity_widget);

      mWidgetProvider = TorchWidgetProvider.getInstance();

      mColor = (ListPreference) findPreference(KEY_WIDGET_COLOR);
      if(mColor.getValue()==null){
          mColor.setValueIndex(0);
      }
      mColor.setSummary(mColor.getValue().toString());
      mColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(Preference preference, Object newValue) {
              preference.setSummary(newValue.toString());
              String mPrefColor = newValue.toString();
              Utils.colorizeBar(mActivity, mContext, mPrefColor);
              return true;
          }
      });

      Bundle extras = getIntent().getExtras();
      if (extras != null) {
          mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                  AppWidgetManager.INVALID_APPWIDGET_ID);
      }

      mPreferences.registerOnSharedPreferenceChangeListener(this);
  }
 
Example 15
Source File: SingleWebsitePreferences.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize a ListPreference with a certain value.
 * @param preference The ListPreference to initialize.
 * @param value The value to initialize it to.
 */
private void setUpListPreference(Preference preference, ContentSetting value) {
    if (value == null) {
        getPreferenceScreen().removePreference(preference);
        return;
    }

    ListPreference listPreference = (ListPreference) preference;

    int contentType = getContentSettingsTypeFromPreferenceKey(preference.getKey());
    CharSequence[] keys = new String[2];
    CharSequence[] descriptions = new String[2];
    keys[0] = ContentSetting.ALLOW.toString();
    keys[1] = ContentSetting.BLOCK.toString();
    descriptions[0] = getResources().getString(
            ContentSettingsResources.getSiteSummary(ContentSetting.ALLOW));
    descriptions[1] = getResources().getString(
            ContentSettingsResources.getSiteSummary(ContentSetting.BLOCK));
    listPreference.setEntryValues(keys);
    listPreference.setEntries(descriptions);
    int index = (value == ContentSetting.ALLOW ? 0 : 1);
    listPreference.setValueIndex(index);
    int explanationResourceId = ContentSettingsResources.getExplanation(contentType);
    if (explanationResourceId != 0) {
        listPreference.setTitle(explanationResourceId);
    }

    if (listPreference.isEnabled()) {
        SiteSettingsCategory category =
                SiteSettingsCategory.fromContentSettingsType(contentType);
        if (category != null && !category.enabledInAndroid(getActivity())) {
            listPreference.setIcon(category.getDisabledInAndroidIcon(getActivity()));
            listPreference.setEnabled(false);
        } else {
            listPreference.setIcon(ContentSettingsResources.getIcon(contentType));
        }
    } else {
        listPreference.setIcon(getDisabledInChromeIcon(contentType));
    }

    preference.setSummary("%s");
    listPreference.setOnPreferenceChangeListener(this);
}
 
Example 16
Source File: SettingsActivity.java    From your-local-weather with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref_updates);

    SensorManager senSensorManager  = (SensorManager) getActivity()
            .getSystemService(Context.SENSOR_SERVICE);
    Sensor senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    boolean deviceHasAccelerometer = senSensorManager.registerListener(
            sensorListener,
            senAccelerometer,
            SensorManager.SENSOR_DELAY_FASTEST);
    senSensorManager.unregisterListener(sensorListener);

    Preference updateWidgetUpdatePref = findPreference(Constants.KEY_PREF_LOCATION_AUTO_UPDATE_PERIOD);
    ListPreference updateListPref = (ListPreference) updateWidgetUpdatePref;
    int accIndex = updateListPref.findIndexOfValue("0");

    if (!deviceHasAccelerometer) {
        CharSequence[] entries = updateListPref.getEntries();
        CharSequence[] newEntries = new CharSequence[entries.length - 1];
        int i = 0;
        int j = 0;
        for (CharSequence entry : entries) {
            if (i != accIndex) {
                newEntries[j] = entries[i];
                j++;
            }
            i++;
        }
        updateListPref.setEntries(newEntries);
        if (updateListPref.getValue() == null) {
            updateListPref.setValueIndex(updateListPref.findIndexOfValue("60") - 1);
        }
    } else if (updateListPref.getValue() == null) {
        updateListPref.setValueIndex(accIndex);
    }
    LocationsDbHelper locationsDbHelper = LocationsDbHelper.getInstance(getActivity());
    List<Location> availableLocations = locationsDbHelper.getAllRows();
    boolean oneNoautoLocationAvailable = false;
    for (Location location: availableLocations) {
        if (location.getOrderId() != 0) {
            oneNoautoLocationAvailable = true;
            break;
        }
    }
    if (!oneNoautoLocationAvailable) {
        ListPreference locationPreference = (ListPreference) findPreference("location_update_period_pref_key");
        locationPreference.setEnabled(false);
    }

    ListPreference locationAutoPreference = (ListPreference) findPreference("location_auto_update_period_pref_key");
    locationAutoPreference.setEnabled(locationsDbHelper.getLocationByOrderId(0).isEnabled());
}
 
Example 17
Source File: SingleWebsitePreferences.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize a ListPreference with a certain value.
 * @param preference The ListPreference to initialize.
 * @param value The value to initialize it to.
 */
private void setUpListPreference(Preference preference, ContentSetting value) {
    if (value == null) {
        getPreferenceScreen().removePreference(preference);
        return;
    }

    ListPreference listPreference = (ListPreference) preference;

    int contentType = getContentSettingsTypeFromPreferenceKey(preference.getKey());
    CharSequence[] keys = new String[2];
    CharSequence[] descriptions = new String[2];
    keys[0] = ContentSetting.ALLOW.toString();
    keys[1] = ContentSetting.BLOCK.toString();
    descriptions[0] = getResources().getString(
            ContentSettingsResources.getSiteSummary(ContentSetting.ALLOW));
    descriptions[1] = getResources().getString(
            ContentSettingsResources.getSiteSummary(ContentSetting.BLOCK));
    listPreference.setEntryValues(keys);
    listPreference.setEntries(descriptions);
    int index = (value == ContentSetting.ALLOW ? 0 : 1);
    listPreference.setValueIndex(index);
    int explanationResourceId = ContentSettingsResources.getExplanation(contentType);
    if (explanationResourceId != 0) {
        listPreference.setTitle(explanationResourceId);
    }

    if (listPreference.isEnabled()) {
        SiteSettingsCategory category =
                SiteSettingsCategory.fromContentSettingsType(contentType);
        if (category != null && !category.enabledInAndroid(getActivity())) {
            listPreference.setIcon(category.getDisabledInAndroidIcon(getActivity()));
            listPreference.setEnabled(false);
        } else {
            listPreference.setIcon(ContentSettingsResources.getIcon(contentType));
        }
    } else {
        listPreference.setIcon(
                ContentSettingsResources.getDisabledIcon(contentType, getResources()));
    }

    preference.setSummary("%s");
    listPreference.setOnPreferenceChangeListener(this);
}
 
Example 18
Source File: SingleWebsitePreferences.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize a ListPreference with a certain value.
 * @param preference The ListPreference to initialize.
 * @param value The value to initialize it to.
 */
private void setUpListPreference(Preference preference, ContentSetting value) {
    if (value == null) {
        getPreferenceScreen().removePreference(preference);
        return;
    }

    ListPreference listPreference = (ListPreference) preference;

    int contentType = getContentSettingsTypeFromPreferenceKey(preference.getKey());
    CharSequence[] keys = new String[2];
    CharSequence[] descriptions = new String[2];
    keys[0] = ContentSetting.ALLOW.toString();
    keys[1] = ContentSetting.BLOCK.toString();
    descriptions[0] = getResources().getString(
            ContentSettingsResources.getSiteSummary(ContentSetting.ALLOW));
    descriptions[1] = getResources().getString(
            ContentSettingsResources.getSiteSummary(ContentSetting.BLOCK));
    listPreference.setEntryValues(keys);
    listPreference.setEntries(descriptions);
    int index = (value == ContentSetting.ALLOW ? 0 : 1);
    listPreference.setValueIndex(index);
    int explanationResourceId = ContentSettingsResources.getExplanation(contentType);
    if (explanationResourceId != 0) {
        listPreference.setTitle(explanationResourceId);
    }

    if (listPreference.isEnabled()) {
        SiteSettingsCategory category =
                SiteSettingsCategory.fromContentSettingsType(contentType);
        if (category != null && !category.enabledInAndroid(getActivity())) {
            listPreference.setIcon(category.getDisabledInAndroidIcon(getActivity()));
            listPreference.setEnabled(false);
        } else {
            listPreference.setIcon(ContentSettingsResources.getIcon(contentType));
        }
    } else {
        listPreference.setIcon(
                ContentSettingsResources.getDisabledIcon(contentType, getResources()));
    }

    preference.setSummary("%s");
    listPreference.setOnPreferenceChangeListener(this);
}
 
Example 19
Source File: GroupSettingsFragment.java    From snapdroid with GNU General Public License v3.0 4 votes vote down vote up
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.group_preferences);
        PreferenceScreen screen = this.getPreferenceScreen();

        prefStreams = (ListPreference) findPreference("pref_stream");

        Bundle bundle = getArguments();
        try {
            group = new Group(new JSONObject(bundle.getString("group")));
            serverStatus = new ServerStatus(new JSONObject(bundle.getString("serverStatus")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        final ArrayList<Stream> streams = serverStatus.getStreams();
        final CharSequence[] streamNames = new CharSequence[streams.size()];
        final CharSequence[] streamIds = new CharSequence[streams.size()];
        for (int i = 0; i < streams.size(); ++i) {
            streamNames[i] = streams.get(i).getName();
            streamIds[i] = streams.get(i).getId();
        }

        prefStreams.setEntries(streamNames);
        prefStreams.setEntryValues(streamIds);

        for (int i = 0; i < streams.size(); ++i) {
            if (streamIds[i].equals(group.getStreamId())) {
                prefStreams.setTitle(streamNames[i]);
                prefStreams.setValueIndex(i);
                oldStream = prefStreams.getValue();
                break;
            }
        }

        prefStreams.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                for (int i = 0; i < streams.size(); ++i) {
                    if (streamIds[i].equals(newValue)) {
                        prefStreams.setTitle(streamNames[i]);
//                        client.getConfig().setStream(streamIds[i].toString());
                        prefStreams.setValueIndex(i);
                        break;
                    }
                }

                return false;
            }
        });


        prefCatClients = (PreferenceCategory) findPreference("pref_cat_clients");
        ArrayList<CheckBoxPreference> allClients = new ArrayList<>();
        for (Group g : serverStatus.getGroups()) {
            for (Client client : g.getClients()) {
                CheckBoxPreference checkBoxPref = new CheckBoxPreference(screen.getContext());
                checkBoxPref.setKey(client.getId());
                checkBoxPref.setTitle(client.getVisibleName());
                checkBoxPref.setChecked(g.getId().equals(group.getId()));
                checkBoxPref.setPersistent(false);
                allClients.add(checkBoxPref);
            }
        }
        Collections.sort(allClients, new Comparator<CheckBoxPreference>() {
            @Override
            public int compare(CheckBoxPreference lhs, CheckBoxPreference rhs) {
                return lhs.getTitle().toString().compareToIgnoreCase(rhs.getTitle().toString());
            }
        });
        for (CheckBoxPreference pref : allClients)
            prefCatClients.addPreference(pref);

        oldClients = getClients().toString();
    }