How can I change the view of a CheckBoxPreference at runtime?
Specifically, I'd like to change a CheckBoxPreference summary depending on whether the user has checked the box or not.
If it were a normal view, I could do something like:
view1 = (TextView)findViewById(R.id.idView1);
view1.setText("some text");
But a CheckBoxPreference has no id, so I don't know how to get a "handle" to it.
I have an answer to my own question. The key is to use findPreference in a PreferenceActivity, as follows:
public class MyPreferenceActivity extends PreferenceActivity{
private SharedPreferences preferences;
private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
private CheckBoxPreference pref;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
pref = (CheckBoxPreference) findPreference(res.getString(R.string.keyAccount));
pref.setSummary("something");
//-- preference change listener
prefListener = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key){
if (key.equals(somekey)){
pref.setSummary("something new");
}
}
};
preferences.registerOnSharedPreferenceChangeListener(prefListener);
}
This is tested and works.
You should use (in XML layout file):
android:summaryOff
android:summaryOn
You can set id to CheckBoxPreference using android:id in xml like code below
<CheckBoxPreference
android:key="pref_boot_startup"
android:title="Auto start"
android:defaultValue="true"
android:id="#+id/my_CheckBoxPref"
/>
To retrieve you can use
CheckBoxPreference check = (CheckBoxPreference)findViewById(R.id.my_CheckBoxPref);
Related
I am currently able to create a preference screen with a PreferenceFragment, in which I assign my preferences using:
addPreferencesFromResource(R.xml.preferences);
Instead of using the resource 'R.xml.preferences', I would like to use my SharedPreferences i have already saved, for example:
SharedPreferences prefs = this.getActivity().getSharedPreferences("preferences", 0);
addPreferencesFromResource(prefs);
However, this does not work. Is it possible to do this? If so, How? Or is it required that I use an xml document?
I happen to had exactly the same problem but I figured it out, hope this helps.
You need to do the following steps in order to add a Custom Preference without using an XML Reouser
First:
You need to create a Preference Screen, this is as it says a "screen" which can containt several Preferences and must be linked to your PreferenceFragment or PreferenceActivity.
Consider the Following PreferenceFragment for example (and consider it is contained in a superior Activity..)
public static class YourPreferenceFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceScreen p = createPreferences();
this.setPreferenceScreen(p);//Set the PreferenceScreen as the current one on this fragment
//now bind values, notice we use p.findPreference which means whe look into the preferenceScreen Associated with the PreferenceFragment/Activity
bindPreferenceSummaryToValue(p.findPreference("some_key"));
}
}
Now Consider that createPreferences is a method that will return a PreferenceScreen with your custom preferences such as a ListPreference or CheckboxPreference. This is how you really create the preferences and add them into a PreferenceScreen
private PreferenceScreen createPreferences()
{
PreferenceScreen p =
getPreferenceManager().createPreferenceScreen(getActivity());
ListPreference listPref = new ListPreference(getActivity());
listPref.setKey("some_key"); //Refer to get the pref value
CharSequence[] csEntries = new String[]{"Item1","Item2"};
CharSequence[] csValues = new String[]{"1","2"};
listPref.setDefaultValue(-1);
listPref.setEntries(csEntries); //Entries(how you display them)
listPref.setEntryValues(csValues);//actual values
listPref.setDialogTitle("Dialog title");
listPref.setTitle("Title");
listPref.setSummary("Some summary");
p.addPreference(listPref);
return p;
}
Please let me know if this helps
best,
EDIT: Code for bindPreferenceSummaryToValue
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
if (preference instanceof CheckBoxPreference) {
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.
getDefaultSharedPreferences(preference.getContext()).
getBoolean(preference.getKey(),false));
} else {
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.
getDefaultSharedPreferences(preference.getContext()).
getString(preference.getKey(),""));
}
}
I have EditText in preferences and I also have EditText in my layout.So I want to get string from Preferences and use it for EditText when i click my button.So i tried like this :
public class MainActivity extends Activity{
SharedPreferences sharedPreferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
}
//OnClick method
public void Button(View view) {
EditText et1 = (EditText) findViewById(R.id.edittext);
String string = sharedPreferences
.getString("ime", "default");
et1.setText(String.valueOf(string));
}
and my prefs xml :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference android:title="Uredi Text"
android:key="ime"
android:summary="ime pjesme"
/>
</PreferenceScreen>
And Everytime when I click the button EditText text becomes "default"
Do not use getBaseContext() directly - use "local context", which in your case is Activity (as activty extends Context). So in your example code, replace it with this:
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences( this );
How do I update my PreferenceActivity?
I've saved in the SharedPreferences the value of my CheckBox in an activity (in that case, true). And even if I go to other activities I can see that it's true. But, when I go to my PreferenceActivity, the checkbox is not checked, it's false. So what I want to know is, how do I load my SharedPreferences in my PreferenceActivity, and how do I update the CheckBox (load the value, and if it's true, set the CheckBox as checked).
Should I load it like this?
Shared Preferences SP = getSharedPreferences(DATA, MODE_PRIVATE);
fw = SP.getBoolean("fw", false);
But, how do I set the CheckBox true or false since I can't use findViewById?
EDIT:
Activity where I save the CheckBox value:
Editor edit = SP.edit();
edit.putBoolean("fw", fwbt.isChecked());
edit.commit();
My preference xml file:
<CheckBoxPreference
android:title="CheckBox FW"
android:key="fw"
android:summary="Estado do CheckBox" />
My preference Activity:
public class Prefs extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
//Don't know what to do here...
}
}
You need to create an Editor to modify the SharedPreferences.
Example
getSharedPreferences(DATA, MODE_PRIVATE).edit().putBoolean("fw", true).commit();
Update
You need to define the used SharedPreferences in the Activity, too.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(DATA);
addPreferencesFromResource(R.xml.prefs);
}
I have not use PreferenceActivity before but I think you simply need to implement it like any other activity.
public class PreferenceWithHeaders extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CheckBox cb = (CheckBox)this.findViewById(IDOFBUTTON);
... do whatever on checkbox
}
I can't find a solution, so I gave up. I've just created created a custom Preferences, it's way easier.
Anyway, I'll keep looking for a solution for this later.
You've mess it up - the PreferenceActivity writes/reads from the SharedPreferences. So in your activity do
Shared Preferences SP = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = SP.edit();
edit.putBoolean("fw", fwbt.isChecked());
edit.commit();
and the change should be there in your PreferenceActivity.
Also :
SP.edit().putBoolean("fw", fwbt.isChecked()).commit();
will do
I have a preference activity and have noticed that a list preference does not set default values when changed.
The Preference has these basic dynamics
If Checkbox = unticked --> list preference entry values = x
if Checkbox = ticked --> list preference entry values = z
When the app first runs default value is set but when I tick the checkbox no values apply after that.
CODE:
public class QuickPrefsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
View title =(View)getWindow().findViewById(android.R.id.title);
FrameLayout titlebar=(FrameLayout)title.getParent();
TextView txt = (TextView)titlebar.getChildAt(0);
txt.setGravity(Gravity.CENTER);
CheckBoxPreference chckbox = (CheckBoxPreference)
findPreference("french");
if (chckbox.isChecked()) {
ListPreference newsPref = (ListPreference)
findPreference("news_feed");
newsPref.setEntryValues(getResources().
getStringArray(R.array.newsfeedfr));
newsPref.setDefaultValue(1);
} else {
ListPreference news2Pref = (ListPreference)
findPreference("news_feed");
news2Pref.setEntryValues(getResources().
getStringArray(R.array.newsfeed));
news2Pref.setDefaultValue(1);
}
}
}
you need to add onPreferenceChangeListener like below...
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("french");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("true") {
// add your code here if checkbox is checked.
}
else {
// add your code here if checkbox is not checked.
}
return true;
}
});
Method setDefaultValue() takes an Object as argument, rather than index in values array. So, you should rewrite your code something like this:
String[] values = getResources().getStringArray(R.array.newsfeed)
news2Pref.setEntryValues(values);
news2Pref.setDefaultValue(values[0]);
Moreover, you should probably set entry titles too:
news2Pref.setEntries(your_titles_array_here);
I have made 4 radio buttons and want to save the state when any of them is clicked and then want to use that saved state in the application.How can i do that?
myOption1.setChecked(true);
myOption2.setChecked(true);
myOption3.setChecked(true);
myOption4.setChecked(true);
Override onSaveInstanceState() and onRestoreInstanceState() in your activity.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("myOption1", myOption1.isChecked());
savedInstanceState.putBoolean("myOption2", myOption2.isChecked());
savedInstanceState.putBoolean("myOption3", myOption3.isChecked());
savedInstanceState.putBoolean("myOption4", myOption4.isChecked());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myOption1.setChecked(savedInstanceState.getBoolean("myOption1"));
myOption2.setChecked(savedInstanceState.getBoolean("myOption2"));
myOption3.setChecked(savedInstanceState.getBoolean("myOption3"));
myOption4.setChecked(savedInstanceState.getBoolean("myOption4"));
}
If you're only going to have 4 radio buttons all in all, you might as well store their "values" in SharedPreferences (persistant storage).
Example:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor shEditor = sharedPreferences.edit();
shEditor.putBoolean("checkbox_1", myOptionOne.isChecked());
shEditor.putBoolean("checkbox_2", myOptionTwo.isChecked());
shEditor.putBoolean("checkbox_3", myOptionThree.isChecked());
shEditor.putBoolean("checkbox_4", myOptionFour.isChecked());
shEditor.commit();
Use it by doing the following:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
myOptionOne.setChecked(sharedPreferences.getBoolean("checkbox_1", false));
myOptionTwo.setChecked(sharedPreferences.getBoolean("checkbox_2", false));
myOptionThree.setChecked(sharedPreferences.getBoolean("checkbox_3", false));
myOptionFour.setChecked(sharedPreferences.getBoolean("checkbox_4", false));
Save that value in sharedPreferences Concept. Sample Example has been placed here that uses predefined method called addPreferencesFromResource() that will get the state of checkbox value automatically and saved in the preferences.
public class EditPreference extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.checkboxpref);
addPreferencesFromResource(R.layout.checkboxpref);
}
}
And layout Code should be this :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="#string/checkbox_pref"
android:title="#string/eidt_preferences">
<CheckBoxPreference
android:key="#string/pref_12_time_format"
android:title="#string/time_formats"
android:summary="#string/twelve_hour"
android:defaultValue="true"/>
<CheckBoxPreference
android:key="#string/pref_show_current_location"
android:title="#string/show_current_location"
android:summary="#string/using_gps_network"
android:defaultValue="true"/>
<CheckBoxPreference
android:key="#string/pref_display_date"
android:title="#string/display_date"
android:defaultValue="true"/>
</PreferenceScreen>
Now you have retreive this stored checkbox value has follows :
SharedPreferences sharedPreference = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
mTimeFormat = sharedPreference.getBoolean("pref_12_time_format", false);
mServiceType = sharedPreference.getBoolean(
"pref_show_current_location", false);
mDisplayDate = sharedPreference.getBoolean("pref_display_date", false);