CheckBox PreferenceScreen - android

I am doing a preferenceScreen with this xml code:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:orderingFromXml="true">
<PreferenceCategory
android:key="pref1"
android:title="Search All">
<CheckBoxPreference
android:key="check_all"
android:title="Check"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Specific Search"
android:key="pref2">
<ListPreference
android:title="Food"
android:key="opcion1"
android:dialogTitle="Escoge Categoria"
android:entryValues="#array/codigoCateg"
android:entries="#array/categorias"
android:negativeButtonText="Cancel"/>
<ListPreference android:title="Dificultad"/>
<ListPreference android:title="Otras"/>
</PreferenceCategory>
Java code:
public class OpcionesBusqueda extends PreferenceActivity {
boolean CheckBoxPreference;
private PreferenceCategory Pref2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.video_search);
Pref2=(PreferenceCategory)findPreference("pref2");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
CheckBoxPreference = prefs.getBoolean("check_all", true);
if(CheckBoxPreference==true){
Pref2.setEnabled(false);
}
else{
Pref2.setEnabled(true);
}
}
}
What I would like to do is if the checkbox is checked then the pref2 (preferencecategory2) should be disabled and if it is unchecked, it should be enabled. There is something that I'm doing wrong, or maybe more than one.
Thanks.
I followed Alex's answer and with some changes I arrived to the desire code, here is the code corrected:
public class OpcionesBusqueda extends PreferenceActivity {
private CheckBoxPreference Check;
private PreferenceCategory Pref2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.video_search);
Check=(CheckBoxPreference)findPreference("check_all");
Pref2=(PreferenceCategory)findPreference("pref2");
Check.setOnPreferenceChangeListener(new CheckBoxPreference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
Pref2.setEnabled((Boolean)newValue == false);
return true;
}
});
}

You may want to set OnPreferenceChangeListener for the check_all preference and change pref2 inside onPreferenceChaged of that OnPreferenceChangeListener
CheckBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
boolean onPreferenceChange(Preference preference, Object newValue) {
Pref2.setEnabled((Boolean)newValue == false);
}
}

Related

Android can't figure out why perference screen won't show preference textbox

I'm trying to display preference screen and with a text box and doesn't show but in another screen it has no problem? It shows a negative 1 or null.
StatsActivity
public class StatsActivity extends Activity {
static final String TAG = "StatsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats_settings_layout);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n" + sharedPrefs.getString("time_usage_key", "-1"));
TextView settingsTextViewStats = (TextView) findViewById(R.id.stats_settings_text_view);
settingsTextViewStats.setText(builder.toString());
}
}
StatsPrefsActivity
public class StatsPrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
static final String TAG = "StatsPrefsActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_stats);
PreferenceManager.setDefaultValues(this,R.xml.preferences_stats, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(Menu.NONE, 0, 0, "Show current settings");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, StatsActivity.class));
return true;
}
return false;
}
#Override
public void onStart(){
super.onStart();
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(StatsPrefsActivity.this);
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
}
}
preference_stats.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Settings"
android:key="first_category">
<EditTextPreference
android:id="#+id/text_pref_box"
android:key="time_usage_key"
android:title="7 Day Usage"
android:summary="A total of usage of 7 days." />
</PreferenceCategory>
</PreferenceScreen>
if you want an inital value then set one. right now you have "-1" set as the default value. so if the preference has never been used before your going to get "-1" as the default. Try changing that to a blank string "" or something if you want better presentation.

preferencefragment no view found for id android

I had the getpreferencescreen deprecated so I tryed to implement the header preference activity.
here is my code:
public class EditPreferences extends PreferenceActivity {
ListPreference m_list_preference_dive_centre_rating;
ListPreference m_list_preference_dive_region_rating;
ListPreference m_list_preference_wreck;
ListPreference m_list_preference_cave;
MultyChoiceListPlugin m_list_preference_marine_life;
ListPreference m_list_preference_region;
Preference m_order_by_name;
SharedPreferences.Editor m_editor;
static Context m_context;
int m_order_type_val = 0;
boolean m_wreck_selected = false;
boolean m_cave_selected = false;
boolean m_marine_life_selected = false;
boolean m_region_selected = false;
int number_click_wreck = 0;
int number_click_cave = 0;
int number_click_marine_life = 0;
int number_click_region = 0;
boolean m_without_guide_selected = false;
boolean m_without_equipment_selected = false;
boolean m_budget_selected = false;
boolean m_region_rating = false;
boolean m_centre_rating = false;
private ListView m_preferenceView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//m_order_by_name.setOnPreferenceClickListener(onOrderByNamePrefClick);
final Button back_btn = (Button)this.findViewById(R.id.back);
final Button home_btn = (Button)this.findViewById(R.id.home);
//final Button search_btn = (Button)this.findViewById(R.id.search);
final Button info_btn = (Button)this.findViewById(R.id.info);
back_btn.setOnClickListener(onBackBtn);
home_btn.setOnClickListener(onHomeBtn);
// search_btn.setOnClickListener(onSearchBtn);
info_btn.setOnClickListener(onInfoBtn);
}
/**
* Populate the activity with the top-level headers.
*/
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
public static class Prefs1Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.wrap_preferences);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.layout.wrap_preferences, false);
addPreferencesFromResource(R.xml.preferences1);
}
}
public static class Prefs2Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences2);
}
}
public static class Prefs3Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
// PreferenceManager.setDefaultValues(getActivity(),
// R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences3);
}
}
private View.OnClickListener onBackBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","last_from");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
private View.OnClickListener onHomeBtn = new OnClickListener() {
public void onClick(View v) {
//set the view for dive center list ordered by rating
//set the result to the callback of the parent activitie
Intent intent_call_back = new Intent();
intent_call_back.putExtra("goback","home");
setResult(DivingReview.CALL_BACK,intent_call_back);
finish();
}
};
I've got the error:No view found for id 0x1020343 (android:id/prefs) for fragment
XML code pref_headers.xml:
<?xml version="1.0" encoding="UTF-8"?>
<preference-headers
xmlns:android="http://schemas.android.com/apk/res/android" >
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs1Fragment"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs2Fragment"
android:title="#string/what_is_your_budget_text"
android:summary="#string/what_is_your_budget_summary" >
</header>
<header android:fragment="com.freelancerobotics.DivingReview.EditPreferences$Prefs3Fragment"
android:title="#string/order_by_name_title"
android:summary="#string/order_by_name_summary">
</header>
<!-- <header
android:icon="#drawable/icon_question"
android:title="Blackmoon Info Tech Services"
android:summary="link to BITS blog">
<intent android:action="android.intent.action.VIEW"
android:data="http://www.blackmoonit.com/2012/07/all_api_prefsactivity/" />
</header>
-->
XML code preferences1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/pref_style"
android:key="who_is_the_best"
android:title="#string/who_is_the_best_text"
android:summary="#string/who_is_the_best_summary">
<PreferenceCategory
android:title="#string/who_is_the_best_dive_centre_text"
android:key="who_is_the_best_dive_centre_category">
<ListPreference
android:key="select_dive_centre_rating"
android:title="#string/select_dive_centre_rating_text"
android:summary="#string/select_dive_centre_rating_summary"
android:entries="#array/search_dive_centre_names"
android:entryValues="#array/search_dive_centre_clauses"
android:dialogTitle="#string/search_dive_centre_choice_title"/>
</PreferenceCategory>
</PreferenceScreen>
thanks in advance
The official documentation is misleading:
Removing the onCreate function in public class EditPreferences extends PreferenceActivity resolves the issue.
I just moved what was in onCreate to onBuildHeaders function.
I was having this problem too, until I realized that I had specified the wrong layout in setContentView() of the onCreate() method of the FragmentActivity.
The id passed into FragmentTransaction.add(), in your case R.id.feedContentContainer, must be a child of the layout specified in setContentView().
You didn't show us your onCreate() method, so perhaps this is the same problem.

Setting CheckBoxPreference from SharedPreference

I'd like to use pre-defined shared preferences to set the value of a checkBoxPreference, and to set the shared preference with the checkBoxPreference. I tried this code, but checkboxPref always ends up being null even though I know "pre_definied_shared_prefs" exist.
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("pre_defined_shared_prefs");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean b = (Boolean) newValue;
Intent i = getIntent();
Integer show_num = i.getIntExtra("show_num", -1);
SettingsManager s = new SettingsManager();
s.setShowNotification(show_num, b, getApplicationContext());
return true;
}
});
Why would this be and how can I fix it?
My preference.xml:
<CheckBoxPreference
android:title="Show Call UI"
android:defaultValue="true"
android:summary="Show Call Interface when clicking call button"
android:key="checkboxPref" />
Rest code:
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());
return true;
}
});
Here is the example on how to create new checkbox preference and add it to the group you wished or look at 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);
}
}

Android: update ListPreference with OnPreferenceChangeListener

Here's my preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<ListPreference
android:key="KEY_1"
android:title="Title"
android:summary="Summary"
android:dialogTitle="Dialog"
/>
<ListPreference
android:key="KEY_2"
/>
<ListPreference
android:key="KEY_3"
/>
<ListPreference
android:key="KEY_4"
/>
And here is the Settings.java:
public class Settings extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// some methods to generate entries and values for ListPreference
final List List_1 = // something
final List List_2 = // something
final List List_3 = // something
String[] entry_1 = List_1.toArray(new String[List_1.size()]);
String[] entry_2 = List_2.toArray(new String[List_2.size()]);
String[] entry_3 = List_3.toArray(new String[List_3.size()]);
String[] value_1 = List_1.toArray(new String[List_1.size()]);
String[] value_2 = List_2.toArray(new String[List_2.size()]);
String[] value_3 = List_3.toArray(new String[List_3.size()]);
// set arrays for entries and values
final ListPreference lp1 = (ListPreference)findPreference("KEY_1");
lp1.setEntries(entry_1);
lp1.setEntryValues(value_2);
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setEntries(entry_2);
lp2.setEntryValues(value_1);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setEntries(entry_2);
lp3.setEntryValues(value_2);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setEntries(entry_2);
lp4.setEntryValues(value_3);
// update lp2, lp3, lp4
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String listValue = (String) newValue;
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setDefaultValue(listValue);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setDefaultValue(listValue);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setDefaultValue(listValue);
return true;
}
});
}
}
This works well for me for only one time. What am I missing here to make the updates on lp2, lp3 and lp4 later on? I guess setDefaultValue creates just that one-time-input to shared preferences?
I suspect your anonymous listener is garbage collected - add some debug prints to see if the listener is called
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("Listener", "I listen");
String listValue = (String) newValue;
// rest is the same
}
});
If you see no debug print move your listener to a class field and :
public class Settings extends PreferenceActivity {
private OnPreferenceChangeListener mListener=new OnPreferenceChangeListener(){
#Override
public boolean onPreferenceChange(Preference preference, Object newValue){
// as before
}
};
// etc - I guess the line below is in onCreate() - correct your formatting !
lp1.setOnPreferenceChangeListener(mListener);
}
}

Custom EditTextPreference and setOnPreferenceChangeListener not called

My listener is not getting called for some reason? This is what I have:
In Preference file I have a custom EditTextPreference:
<com.xxx.yyy.preference.PreferenceEditTextDialog
android:layout="#layout/preference_edit"
android:title="#string/title"
android:summary="#string/summary"
android:defaultValue=""
android:dialogTitle="#string/dialogTitle"
android:key="mypref"/>
I extend my class:
public class PreferenceEditTextDialog extends EditTextPreference {
Launching my Activity:
startActivity(new Intent(this, PrefsActivity.class));
Definition:
public class PrefsActivity extends PreferenceActivity implements
OnPreferenceClickListener, OnSharedPreferenceChangeListener {
In here I register my setOnPreferenceChangeListener (which is not called).
However changing my Preference file from:
<com.xxx.yyy.preference.PreferenceEditTextDialog
to default:
<EditTextPreference
it all works. Could someone help me to find the problem, somehow the listener is not propagated properly using my custom Preference.
Thanks!
#Sam Here my listener definition:
myfield = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREFERENCE);
myfield.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean valid = true;
if(!validate(newValue.toString())) {
valid = false;
}
return valid;
}
});
Found a solution, in my custom EditTextPreference I added a call to callChangeListener(value):
#Override
public void onBindDialogView(View view) {
edittext = (EditText) view.findViewById(R.id.edittext);
edittext.setText(PreferenceManager.
getDefaultSharedPreferences(view.getContext()).
getString(getKey(), ""));
ok_button = (Button) view.findViewById(R.id.ok_button);
ok_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String value = edittext.getText().toString();
if(callChangeListener(value)) {
Editor editor = getEditor();
editor.putString(getKey(), value);
editor.commit();
getDialog().dismiss();
}
}
});

Categories

Resources