In my setting page I have a preference which fetches a list of toggle-able settings that I wanted to display as individual checkbox preferences.
I know that preferences.xml supports generating lists of preferences (looking at wi-fi settings page) but ListPreference only allows you to select one from the list.
I've been searching for how to generate preferences programmatically but have only managed to find how to change attributes of preferences that are already in the XML.
Here is a short example (assuming you are extending PreferenceActivity):
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);
PreferenceCategory category = new PreferenceCategory(this);
category.setTitle("category name");
screen.addPreference(category);
CheckBoxPreference checkBoxPref = new CheckBoxPreference(this);
checkBoxPref.setTitle("title");
checkBoxPref.setSummary("summary");
checkBoxPref.setChecked(true);
category.addPreference(checkBoxPref);
setPreferenceScreen(screen);
}
Programatically add a preference, with other preferences in xml file:
Other solutions didn't work for me because I ALSO had an xml with preferences. I'm not sure all these calls are necessary/redundant, but this works.
onCreate() method, class extends PreferenceActivity:
setContentView(R.layout.preferences);
addPreferencesFromResource(R.xml.preferences);
PreferenceScreen pScreen = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference cb = new CheckBoxPreference(this);
cb.setKey("cb");
cb.setTitle("BLAH");
cb.setOrder(99); //not working...
pScreen.addPreference(cb);
setPreferenceScreen(pScreen);
addPreferencesFromResource(R.xml.preferences);
Sidenote: Since I needed to generate a dynamic checkbox list, it was best suited inside an inner PreferenceScreen. So I created this PreferenceScreen inside the xml, then dynamically generated the checkboxes inside this. This way the ordering didn't matter since all the 'new' dynamica checkboxes were inside this screen.
Try the below code.
CheckBoxPreference checkBoxPref = findPreference("your_key");
if (checkBoxPref != null)
{
checkBoxPref.setChecked(false);
}
Related
Hi I want to create preferences in my application but I cannot use resources at all due to some dependency issues.
I am able to do this using the below code:
public class DTMainActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPreferenceScreen(defaultPref());
setDependencies();
}
// The first time application is launched this should be read
private PreferenceScreen defaultPref() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
SwitchPreference dLogTracingEnablePref = new SwitchPreference(this);
dLogTracingEnablePref.setTitle(R_Class.R_String.dLogTracingEnablePrefString);
dLogTracingEnablePref.setDisableDependentsState(false);
dLogTracingEnablePref.setChecked(true);
dLogTracingEnablePref.setKey(R_Class.R_String.dLogTracingEnablePrefKey);
root.addPreference(dLogTracingEnablePref);
}
I would want to do this using the new fragment based approach, without using the deprecated APIs like getPreferenceManager etc.. I can create all the other UI layout elements like linearlayout etc.. without any resources, but when it comes to preferences and PreferenceFragment class, all that is available is addPreferencesFromResource() which would need an XML. Can any one help me here please?
I managed to made it using a PreferenceFragment, without addPreferencesFromResource(),
Instead I just created the PreferenceScreen like you just did and used
try using the bindPreferenceSummaryToValue, consider "p" being a PreferenceScreen with Preferences already added into it, (and also that has been created and configured previously)
PreferenceScreen p = createPreferences();//a method that creates a PreferenceScreen and add some preferences into it
this.setPreferenceScreen(p);
bindPreferenceSummaryToValue(p.findPreference("preference_key"));
I responded to someone with a similar problem here .. perhaps you can check it out
I want to open some preferences (which are made by extending DialogPreference) on first app startup. Also, these preferences are used as usual preferences.
Is there a way of accomplishing this?
EDIT:
I have my custom preference, made like this:
public class CitySelectPreference extends DialogPreference {
// Some code here
}
And as the solution I want it to be shown from the code, without the need of user getting to preference screen.
Just do this :
CitySelectPreference preference = (CitySelectPreference) findPreference("city_pref_key")
//You have to set a key to yout PreferenceScreen
PreferenceScreen screen = (PreferenceScreen) findPreference("screen_pref_key");
//Retrieve the index of the preference in preferenceScreen
int index = preference.getOrder();
//Perform a click
screen.onItemClick(null, null, index, 0);
I am currently building out a list of rows with checkboxes dynamically using content from a web service. However, this ListView will need to do pretty much what a PreferenceActivity would accomplish.
I don't know the number of rows as the content is dynamic so I can't create each CheckBoxPreference in XML. How do I go about building a PreferenceActivity that will display an unknown number rows with a CheckBoxPreference dynamically?
I think you're looking for something like this:
public class MyPreferenceActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.my_preference_activity);
//fetch the item where you wish to insert the CheckBoxPreference, in this case a PreferenceCategory with key "targetCategory"
PreferenceCategory targetCategory = (PreferenceCategory)findPreference("targetCategory");
//create one check box for each setting you need
CheckBoxPreference checkBoxPreference = new CheckBoxPreference(this);
//make sure each key is unique
checkBoxPreference.setKey("keyName");
checkBoxPreference.setChecked(true);
targetCategory.addPreference(checkBoxPreference);
}
}
Well #Jodes, actually both of you are right, but the correct way of doing this would be using a ListPreference.
I would use a entire programmatic approach, from my experience it's easier to be consistent; either create an entire XML layout via code, or via XML, but mixing the 2 can be weird and you cannot alter everything set via XML...
onCreate(){
this.setPreferenceScreen(createPreferenceHierarchy());
}
public PreferenceScreen createPreferenceHierarchy(){
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
// category 1 created programmatically
PreferenceCategory cat1 = new PreferenceCategory(this);
cat1.setTitle("title");
root.addPreference(cat1);
ListPreference list1 = new ListPreference(this);
list1.setTitle(getResources().getString(R.string.some_string_title));
list1.setSummary(getResources().getString(R.string.some_string_text));
list1.setDialogTitle(getResources().getString(R.string.some_string_pick_title));
list1.setKey("your_key");
CharSequence[] entries = calendars.getCalenders(); //or anything else that returns the right data
list1.setEntries(entries);
int length = entries.length;
CharSequence[] values = new CharSequence[length];
for (int i=0; i<length; i++){
CharSequence val = ""+i+1+"";
values[i] = val;
}
list1.setEntryValues(values);
cat1.addPreference(list1);
return root;
}//end method
However, using this approach you will run into the platform's limitations of not having a multiple select ListPreference, and you'll probably want to implement something else.
I found this solution, which works great. You'll have to read the comments to find clues about how to debug the code though...
You need a ListView for that, a PreferenceActivity. As discussed in this link, PreferenceActivity should only be used for actually saving preferences.
Instead you could either create a simple dialog with single or multiple choice options:
http://developer.android.com/guide/topics/ui/dialogs.html
Or use a ListView as in the API examples Google provides, they give a simple example:
http://hi-android.info/docs/resources/samples/ApiDemos/src/com/example/android/apis/view/List10.html
Use PreferenceFragmentCompat from Preference Compat Library
compile 'com.android.support:preference-v7:23.4.0'
Check this article for the implementation details https://medium.com/#arasthel92/dynamically-creating-preferences-on-android-ecc56e4f0789#.71ssvjses
In my application, I am attempting to use sharedPreferences to save some basic settings as well as a Preference Screen. The name for my sharedPreferences is appPrefs and thus my file name is .../appPrefs.xml
However, my app screen saves it's preferences in the defaultSharedPreference file which is com.COMPANY.PACKAGENAME_preferences.xml
What I would like to do is have my preference screen read/write its preferences to the appPrefs file. I have looked in the API and can't find anything. Am I stuck managing two sharedPreference files?
Just to answer the question about how to use different shared settings name with the new PreferenceFragment API, you need to add the following code when overriding onCreate:
public static class PrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager manager = getPreferenceManager();
manager.setSharedPreferencesName("YOUR_SETTINGS_NAME");
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
Did you try:
PreferenceManager.setSharedPreferencesName
I have multiple views that come and go as the application runs. I want each view to have its own personal preferences that are stored as the ID tag of the view. Above these is the "General Preferences" that the sub prefs reference to get their default values when a view it is created.
Right now I have it set up that the General Preferences are the default SharedPreferences. But I have no Idea how to create the new preferences and set up an activity UI so the user can change them. Is it pretty much the same as setting up the SharedPreferences?
this may not be exactly what you're asking for, but here's what I do:
in my main activity, when I call the preferences activity, I pass it the name of the custom preference file as extra data in the intent:
static final String EXTRA_PREFERENCES_NAME = "android.intent.extra.PREFERENCES_NAME";
...
Intent intent = new Intent(this, Preferences.class);
intent.putExtra(EXTRA_PREFERENCES_NAME, preferencesName);
startActivity(intent);
then, in my preferences activity, I get the custom preferences name and set it like this:
public class Preferences extends PreferenceActivity {
private String preferencesName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the custom preferences name from the extra data in the intent
preferencesName = getIntent().getExtras().getString(MainActivity.EXTRA_PREFERENCES_NAME);
// set the preferences file name
getPreferenceManager().setSharedPreferencesName(preferencesName);
// get the default preferences from XML
addPreferencesFromResource(R.xml.preferences);
}
lastly, in my main activity, I get specific preferences like this:
SharedPreferences preferences = getSharedPreferences(preferencesName, MODE_PRIVATE);
String somePreference = preferences.getString("somePreference", defaultValue);
Somehow I am not worthy to comment but to write an answer, so here we go:
I'd really like to know how to use sharedPreferences with PreferencesActivity instead of DefaultSharedPreferences.
One way I can think of to accomplish this is letting the preferenceActivity save the values to defaultSharedPreferences and then read these values out and save them into a sharedPreferences associated with a name that would match the kind of values saved.
But this seems very wrong. So how do you guys do this? Or do you save all your values from any PreferencesActivties into defaultSharedPreferences?
You can use PreferenceManager to achieve the objective.