I have a CheckBoxPreference and two EditTextPreferences which are dependent on the CheckBoxPreference (all defined in an xml file and all three together inside a single PreferenceScreen).
My question is this: How to hide and redisplay those two EditTextPreferences when the user unchecks and checks the Checkboxpreference respectively?
Currently I am just able to enable/disable them by adding the android:dependency attribute to them.
Solutions to do so in java or in xml will be appreciated. :)
I'm not aware of anyway to do this through xml, which always my preferred choice. But this java solution should work.
CheckBoxPreference chkPref = (CheckBoxPreference)findPreference("myCheckPref");
EditTextPreference editPref1 = (EditTextPreference)findPreference("myEditCheckPref");
PreferenceGroup editTextParent = getParent(editPref1);
chkPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference pref, Object value)
{
if(value)
editTextParent.addPreference(editPref1);
else
editTextParent.removePreference(editPref1);
return true;
}
});
As there is no in built way to find the parent group of a parent, you will also have to define these functions:
private PreferenceGroup getParent(Preference preference)
{
return getParent(getPreferenceScreen(), preference);
}
private PreferenceGroup getParent(PreferenceGroup root, Preference preference)
{
for (int i = 0; i < root.getPreferenceCount(); i++)
{
Preference p = root.getPreference(i);
if (p == preference)
return root;
if (PreferenceGroup.class.isInstance(p))
{
PreferenceGroup parent = getParent((PreferenceGroup)p, preference);
if (parent != null)
return parent;
}
}
return null;
}
Related
I'm generating a listPreference dialog based on xml (entries and entryValues).
<string-array name="listArray">
<item>Title (A-Z)</item>
<item>Title (Z-A)</item>
<item>Visits (default)</item>
<item>Date</item>
<item>Manual</item>
</string-array>
<string-array name="listValues">
<item>titleASC</item>
<item>titleDESC</item>
<item>visitsSort</item>
<item>createSort</item>
<item>manualSort</item>
</string-array>
I want to hide/disable some of the entries (for example: Manual) based on some other parameters.
I understand it should be inside this scope:
Preference sorted = (Preference) findPreference(OPT_SORT);
sorted.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (params) {
What should i put here to hide/disable some of the entries?
}
return true;
}
});
Thank you!
EDIT:
Best solution I found is to load a different set of Entries and EntryValues.
On Preference class (onCreate):
ListPreference sortBy = (ListPreference) findPreference(OPT_SORT);
if (isTabletDevice()) {
sortBy.setEntries(getResources().getStringArray(R.array.HClistArray));
sortBy.setEntryValues(getResources().getStringArray(R.array.HClistValues));
}
Hope this helps anyone! :)
AFAIK, ListPreference does not support this. You might be able to create your own subclass of ListPreference where you use a custom Adapter and indicate which items are and are not enabled.
It's quite late answer, I hope that's will help.
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference
.setSummary(index >= 0 ? listPreference.getEntries()[index]
: null);
// If it's sync_factory_list, enable/disable appropriate settings
if(preference.getKey().equalsIgnoreCase("sync_factory_list")){
Preference p_api_key = preference.getPreferenceManager().findPreference("ws_api_key");
Preference p_api_url = preference.getPreferenceManager().findPreference("ws_api_url");
switch ( index) {
case 0: //local
p_api_key.setEnabled(false);
p_api_url.setEnabled(false);
break;
case 1: //prestashop webservice
p_api_key.setEnabled(true);
p_api_url.setEnabled(true);
break;
case 2: //thrift
p_api_key.setEnabled(false);
p_api_url.setEnabled(false);
break;
default:
p_api_key.setEnabled(false);
p_api_url.setEnabled(false);
break;
}
}
}
...
return true;
}
}
I specifically didn't want to use a radiogroup. I know, I know ... a radiogroup is perfect when you need exclusivity like this.
But..given that I'm working with togglebuttons, how can i disable (setChecked(false)) all (3) other toggle buttons when one of them is checked?
Here is my code for the group of toggle buttons. You need to put your
buttons in the layout where you want them and then use ToggleButtonsGroup object to put them together in a single group.
private class ToggleButtonsGroup implements OnCheckedChangeListener {
private ArrayList<ToggleButton> mButtons;
public ToggleButtonsGroup() {
mButtons = new ArrayList<ToggleButton>();
}
public void addButton(ToggleButton btn) {
btn.setOnCheckedChangeListener(this);
mButtons.add(btn);
}
public ToggleButton getSelectedButton() {
for(ToggleButton b : mButtons) {
if(b.isChecked())
return b;
}
return null;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
uncheckOtherButtons(buttonView.getId());
mDataChanged = true;
} else if (!anyButtonChecked()){
buttonView.setChecked(true);
}
}
private boolean anyButtonChecked() {
for(ToggleButton b : mButtons) {
if(b.isChecked())
return true;
}
return false;
}
private void uncheckOtherButtons(int current_button_id) {
for(ToggleButton b : mButtons) {
if(b.getId() != current_button_id)
b.setChecked(false);
}
}
}
I think you'll need to implement your own radiogroup logic for that. It will need to register itself as the OnCheckedChangeListener for each button it manages.
I wish the API wasn't designed with RadioGroup as a LinearLayout. It would have been much better to separate the radio group management from layout.
I know this has been answered with very good examples, but the way I set mine up is just a tad different so I thought I'd share. It's on a preference list, no ToggleButtonsGroup involved.
#Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals("trailPref") || key.equals("obstaclesPref") || key.equals("insanePref") || key.equals("backgroundBlackPref"))
{
if (key.equals("insanePref"))
{
endurancebox.setChecked(false);
prefsEditor.putBoolean("obstaclesPref", false);
prefsEditor.commit();
}
if (key.equals("obstaclesPref"))
{
insanebox.setChecked(false);
prefsEditor.putBoolean("insanePref", false);
prefsEditor.commit();
}
boolean b = ((CheckBoxPreference) preference).isChecked();
prefsEditor.putBoolean(key, b);
prefsEditor.commit();
}
Log.i(DEBUG_TAG, "Boolean value changed. " + key );
returnPrefs(c);
return false;
}
Also, I'm an Android noob and not too experienced in java either, so it may not be uber efficient, but hey, it works! Could be formatted easily to fit your needs I believe. If the key equals insanePref, I want to turn off obstaclesPref and vice versa. (different game modes, only one can be active at the time.) The other two booleans are unrelated. Also, it puts the preferences into my SharedPreference file, instantiated earlier, along with everything else.
Cheers!
in my app I have nested PreferencesScreen's
<PreferencesScreen>
<PreferencesScreen android:key="application">
</PreferencesScreen>
</PreferencesScreen>
Now I want to fire Intent to take me from currrent Activity directly to application preferences subscreen. How can I do this?
In my application I have the similar task to show second-level PreferencesScreen programmatically. What I did:
In preferences.xml I assigned a key to PreferencesScreen I want to show (as shown in the question).
To show PreferencesScreen I wrote:
final Intent preferencesActivity = new Intent(getBaseContext(), MyPreferencesActivity.class);
preferencesActivity.putExtra("PREFERENCE_SCREEN_KEY", "key_of_preference_screen_to_show");
startActivity(preferencesActivity);
Then in my PreferenceActivity class in method onCreate the following code was added:
final Intent intent = getIntent();
final String startScreen = intent.getStringExtra("PREFERENCE_SCREEN_KEY");
if (startScreen != null) {
getIntent().removeExtra("PREFERENCE_SCREEN_KEY");
final Preference preference = findPreference(startScreen);
final PreferenceScreen preferenceScreen = getPreferenceScreen();
final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
final int itemsCount = listAdapter.getCount();
int itemNumber;
for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
if (listAdapter.getItem(itemNumber).equals(preference)) {
preferenceScreen.onItemClick(null, null, itemNumber, 0);
break;
}
}
}
One remark... Not only second-level PreferencesScreen, but the whole preferences hierarchy was loaded here. So, if you press Back button, the first (parent) PreferencesScreen will appear. In my case that was exactly what I needed. Not sure about yours.
Here is a way of handling the problem by grabbing the child-screen up front:
public class MyChildPreferenceActivity extends PreferenceActivity {
private String screenKey = "myChildScreenKey";
#Override
public PreferenceScreen getPreferenceScreen() {
PreferenceScreen root = super.getPreferenceScreen();
if (root != null) {
PreferenceScreen match = findByKey(root, screenKey);
if (match != null) {
return match;
} else {
throw new RuntimeException("key " + screenKey + " not found");
}
} else {
return null;
}
}
private PreferenceScreen findByKey(PreferenceScreen parent, String key) {
if (key.equals(parent.getKey())) {
return parent;
} else {
for (int i = 0; i < parent.getPreferenceCount(); i++) {
Preference child = parent.getPreference(i);
if (child instanceof PreferenceScreen) {
PreferenceScreen match = findByKey((PreferenceScreen) child, key);
if (match != null) {
return match;
}
}
}
return null;
}
}
// ...
I resolved your exact same issue this way.
In your preference activity:
#Override
protected void onResume() {
super.onResume();
int startingPage = getIntent().getIntExtra(Constants.PREFS_STARTING_PAGE, 0);
switch (startingPage) {
case Constants.MY_PREF_SCREEN_1:
setPreferenceScreen((PreferenceScreen)findPreference(getString(R.string.PREF_SCREEN_1)));
break;
case Constants.MY_PREF_SCREEN_2:
setPreferenceScreen((PreferenceScreen)findPreference(getString(R.string.PREF_SCREEN_2)));
break;
default:
// Nothing to do, but read the warning below.
}
}
Then you can open the inner preference screen with something like this:
Intent prefIntent = new Intent(ctx, MyPreferenceActivity.class);
prefIntent.putExtra(Constants.PREFS_STARTING_PAGE, Constants.MY_PREF_SCREEN_1);
startActivity(prefIntent);
Beware that this works as long as the activity instances are different: one instance for the main preference screen and another for the inner screen. In this way, when you start the activity without "launch" parameter, you always fall into the default switch case and never need to set the main preference screen. The problem here is that if you first run the activity starting with an inner pref screen and then lauch the SAME activity (with the flag singleInstance, for example) asking for the general (root) pref screen, you're not able to call findPreference() to find the root preference screen from inside a child preference screen.
Well, hope to have not made too much confusion ;-)
The way I use is to put nested PreferenceScreen into a separate XML file and use it in other PreferenceActivity. In this case you'll be able to navigate to this screen from preferences using Preference.setIntent() and start this Activity in a usual way from another Activity.
I've an android application with preferences declared in XML, loaded with addPreferencesFromResource. The user can open preferences, click on each item and edit them, all works.
One preference I have is:
<ListPreference android:key="abc"
android:title="#string/abc"
android:summary="#string/cde"
android:persistent="true"/>
How can I show the preference dialog to a user automatically (without the need for the user to go to the preference screen and click on it?).
I tried ( (android.preference.DialogPreference) prefMgr.findPreference( "abc" )).showDialog(null), but is says it is a protected method...? Called it from my main activity (which is a PreferenceActivity), that's why it obviously cannot work. But how else?
EDIT
I just found two threads (1, and 2) with the idea to use findViewById to access the preference, but with no success. It always returns null (does for me, too).
It looks like there is really no possibility to do this from code.
See the new accepted answer for a much cleaner approach! This was working, but not really the clean way of doing it.
Damn it, it got me several hours, but it finally works.
The solution is the undocumented call public void onItemClick (...). It takes several arguments, and as pointed out by this question it can be used to simulate a click according to the index of the element you want to call.
My problem was the item I want to call is deeply nested in an XML-structure. But the solution is very easy: add a key to the PreferenceScreen the item you want to open is in:
<PreferenceScreen
android:key="pref_key"
....
/>
<ListPreference android:key="abc"
android:title="#string/abc"
android:summary="#string/cde"
android:persistent="true"/>
</PreferenceScreen>
And the you can just to the following:
// the preference screen your item is in must be known
PreferenceScreen screen = (PreferenceScreen) findPreference("pref_key");
// the position of your item inside the preference screen above
int pos = findPreference("abc").getOrder();
// simulate a click / call it!!
screen.onItemClick( null, null, pos, 0 );
And the Dialog pops up!
It would be nice to get the PreferenceScreen a Preference is in (so you would not have to know where your Preference is in), because moving the preference/changing the XML could break the automatic dialog silently and might not get noticed (if not tested).
For this I wrote a function which will search through all preferences and return the PreferenceScreen your preference is on, so you don't need to have your PreferenceScreen a key!
private PreferenceScreen findPreferenceScreenForPreference( String key, PreferenceScreen screen ) {
if( screen == null ) {
screen = getPreferenceScreen();
}
PreferenceScreen result = null;
android.widget.Adapter ada = screen.getRootAdapter();
for( int i = 0; i < ada.getCount(); i++ ) {
String prefKey = ((Preference)ada.getItem(i)).getKey();
if( prefKey != null && prefKey.equals( key ) ) {
return screen;
}
if( ada.getItem(i).getClass().equals(android.preference.PreferenceScreen.class) ) {
result = findPreferenceScreenForPreference( key, (PreferenceScreen) ada.getItem(i) );
if( result != null ) {
return result;
}
}
}
return null;
}
private void openPreference( String key ) {
PreferenceScreen screen = findPreferenceScreenForPreference( key, null );
if( screen != null ) {
screen.onItemClick(null, null, findPreference(key).getOrder(), 0);
}
}
// With this, you can call your `Preference` like this from code, you do
// not even have to give your PreferenceScreen a key!
openPreference( "abc" );
You could have extended ListPreference to create your dialog, then included your own public method that calls the protected showDialog method of ListPreference. Something like:
public void show()
{
showDialog(null);
}
This way you won't run into the issue of getOrder() not working when there are PreferenceGroups as several people have pointed out in the comments your answer.
This can be done with any preference types that has a protected showDialog method.
If you use the support library you can open a dialog easily with PreferenceManager.showDialog(Preference).
In your PreferenceFragmentCompat:
getPreferenceManager().showDialog(findPreference("pref_name"));
Note that support preference package has many issues:
non-material styling and
it crashes when rotated with an open dialog.
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("pref_key");
final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
EditTextPreference editPreference = (EditTextPreference) findPreference("set_password_preference");
final int itemsCount = listAdapter.getCount();
int itemNumber;
for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
if (listAdapter.getItem(itemNumber).equals(editPreference)) {
preferenceScreen.onItemClick(null, null, itemNumber, 0);
break;
}
}
}
}
Improving deepak goel's answer:
private void openPreference(String key) {
PreferenceScreen preferenceScreen = getPreferenceScreen();
final ListAdapter listAdapter = preferenceScreen.getRootAdapter();
final int itemsCount = listAdapter.getCount();
int itemNumber;
for (itemNumber = 0; itemNumber < itemsCount; ++itemNumber) {
if (listAdapter.getItem(itemNumber).equals(findPreference(key))) {
preferenceScreen.onItemClick(null, null, itemNumber, 0);
break;
}
}
}
If you're using AndroidX Preference library, it is quite simple.
public class CustomPreferenceFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.your_preference);
DialogPreference dialogPreference = (DialogPreference) findPreference("your_preference_key");
onDisplayPreferenceDialog(dialogPreference);
}
}
wait, u can do something like this as well
Preference p=findPreference("settings_background_color");
p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
int color=PreferenceManager.getDefaultSharedPreferences(ALifePatternsWallpaperSettings.this).getInt("settings_background_color", Color.BLACK);
new ColorPickerDialog(ALifePatternsWallpaperSettings.this, ALifePatternsWallpaperSettings.this, "settings_background_color", color, Color.BLACK).show();
return true;
}
});
hi friends try this code in works fine
getPreferenceManager().findPreference("YOUR PREF_KEY").setOnPreferenceClickListener(new OnPreferenceClickListener()
{
public boolean onPreferenceClick(Preference preference)
{
//your code here
return true;
}
});
Is there a way to dynamically show and hide preferences? In my case, I have a checkbox preference that would disable or enable one of 2 preference groups ("with-" and "without-handicap" groups). While this would be the ideal GUI in a desktop environment, the "with-handicap" takes up nearly the whole screen, while the other, "without-handicap" takes up only a small portion of the screen.
Rather than showing both groups at the same time, I'd like to show only one of them at a time, and dynamically show or hide the 2 groups when the checkbox changes. Is there a way to do this?
From a PreferenceActivity call
Preference somePreference = findPreference(SOME_PREFERENCE_KEY);
PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removePreference(somePreference);
you can later call:
preferenceScreen.addPreference(somePreference);
The only a little bit tricky part is getting the order correct when adding back in. Look at PreferenceScreen documentation, particularly it's base class, PreferenceGroup for details.
Note: The above will only work for immediate children of a PreferenceScreen. If there is a PreferenceCategory in between, you need to remove the preference from its parent PreferenceCategory, not the PreferenceScreen. First to ensure the PreferenceCategory has an android:key attribute set in the XML file. Then:
Preference somePreference = findPreference(SOME_PREFERENCE_KEY);
PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference(SOME_PREFERENCE_CATEGORY_KEY);
preferenceCategory.removePreference(somePreference);
and:
preferenceCategory.addPreference(somePreference);
Not exactly hiding/showing but if you only want disabling/enabling preference depending on another preference you can specify android:dependency="preferenceKey" or Preference.setDependency(String)
Example from developer.android.com:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_sync"
android:title="#string/pref_sync"
android:summary="#string/pref_sync_summ"
android:defaultValue="true" />
<ListPreference
android:dependency="pref_sync"
android:key="pref_syncConnectionType"
android:title="#string/pref_syncConnectionType"
android:dialogTitle="#string/pref_syncConnectionType"
android:entries="#array/pref_syncConnectionTypes_entries"
android:entryValues="#array/pref_syncConnectionTypes_values"
android:defaultValue="#string/pref_syncConnectionTypes_default" />
</PreferenceScreen>
I recommend using V7 preference, it has setVisible() method. But I have not tried it yet.
If you want to implement the hiding of the preference completely in the Preference, here is one example. Does not allow to make it visible again, though.
public class RemovablePreference extends Preference {
#Override
protected void onBindView(View view) {
super.onBindView(view);
updateVisibility(); // possibly a better place available?
}
private void updateVisibility() {
Context context = getContext(); // should be a PreferenceActivity
if (context instanceof PreferenceActivity) {
updateVisibility((PreferenceActivity)context);
}
}
private void updateVisibility(PreferenceActivity activity) {
updateVisibility(getPreferenceScreen(activity));
}
private PreferenceScreen getPreferenceScreen(PreferenceActivity activity) {
if (activity.getPreferenceScreen() != null) {
return activity.getPreferenceScreen(); // for old implementations
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Fragment fragment = activity.getFragmentManager().findFragmentById(android.R.id.content);
if (fragment instanceof PreferenceFragment) {
return ((PreferenceFragment) fragment).getPreferenceScreen();
}
}
return null;
}
private void updateVisibility(PreferenceScreen screen) {
if (!isVisible() && screen != null) {
hidePreference(screen, this);
}
}
private boolean hidePreference(PreferenceGroup prefGroup, Preference removedPreference) {
boolean removed = false;
if (prefGroup.removePreference(removedPreference)) {
removed = true;
}
for (int i = 0; i < prefGroup.getPreferenceCount(); i++) {
Preference preference = prefGroup.getPreference(i);
if (preference instanceof PreferenceGroup) {
PreferenceGroup prefGroup2 = (PreferenceGroup)preference;
if (hidePreference(prefGroup2, this)) {
// The whole group is now empty -> remove also the group
if (prefGroup2.getPreferenceCount() == 0) {
removed = true;
prefGroup.removePreference(prefGroup2);
}
}
}
}
return removed;
}
protected boolean isVisible() {
return true; // override
}
I needed something similar: toggling a switch to hide or show two extra preferences. Check out the sample app from Android-Support-Preference-V7-Fix which bring some new preference types and fixes some issues from the official library. There's an example there to toggle a checkbox to show or hide a preference category.
In the fragment that extends PreferenceFragmentCompatDividers, you could use something like:
findPreference("pref_show_extra_stuff").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
findPreference("pref_extra_stuff_01").setVisible((Boolean) newValue);
findPreference("pref_extra_stuff_02").setVisible((Boolean) newValue);
return true;
}
});
pref_extra_stuff_01 and pref_extra_stuff_02 are the two preferences that are hidden when pref_show_extra_stuff is toggled.
For hiding preferences dynamically, I created an if-condition upon whose value I decide whether I want the pref to show or not. To do the actual hiding, I have been using:
findPreference(getString(R.string.pref_key)).setLayoutResource(R.layout.hidden);
The tricky part is to make it visible again. There is no direct way to do it except to recreate the layout. If the value of the if-condition is false, which means the pref should be visible, then the code to hide the pref will never be executed, thus resulting in a visible pref. Here is how to recreate the layout (in my case, I am extending a PreferencesListFragment):
getActivity().recreate();
I hope that was helpful.
Instead of doing this in onCreate in the settings activity:
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, new SettingsFragment()).commit();
You can initialize a global variable for the settings fragment and set it up like this:
settingsFragment = new SettingsFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, settingsFragment).commit();
Then further down you can set up an OnSharedPreferenceChangeListener with a global SharedPreferences.OnSharedPreferenceChangeListener to set up what should be shown or hidden when you change preferences:
// Global SharedPreferences.OnSharedPreferenceChangeListener
sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key)
{
if (key.equals("switch key"))
{
boolean newPref = preferences.getBoolean("switch key", true);
settingsFragment.findPreference("seekbar key").setVisible(newPref);
}
}
};
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
Then in onCreate in the settings fragment you can do something like this to set what should be hidden based on existing preferences:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
if (!sharedPreferences.getBoolean("switch key", true)
{
SeekBarPreference seekBarPreference = findPreference("seekbar key");
seekBarPreference.setVisible(false);
}