Checkboxpreference change value - android

I have checkboxpreference in preference activity and I want that when one of the checkbox is enabled then other checkbox should get to disable and vice versa.
I wants to do that from my main class activity.
Here is my code:
Preferencecheckbox.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:defaultValue="true"
android:icon="#drawable/img"
android:key="check1"
android:title="first" />
<CheckBoxPreference
android:defaultValue="false"
android:icon="#drawable/img2"
android:key="check2"
android:title="second" />
</PreferenceScreen>
Preferenceclass.java
public class preferenceclass extends PreferenceActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferencecheckbox);
}

You need to add a dependency to the checkbox you need disabled.
Like this:
<CheckBoxPreference
android:defaultValue="false"
android:icon="#drawable/img2"
android:key="check2"
android:title="second"
android:dependency="check1" />
Update
To disable other preferences via code.
final CheckBoxPreference checkbox2 = (CheakBoxPreference) findPreference("pref_checkbox2_key");
CheckBoxPreference switch = (CheakBoxPreference) findPreference("pref_switch_key");
switch.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
if (switch.isChecked()) {
checkbox2.setEnabled(false);
} else {
checkbox2.setEnabled(true);
}
return true;
}
});
persistCheckBoxState(switch, checkbox2);
To persist the change when activity is closed, you need to get the preferences references like this and add directly below.
public void persistCheckBoxState (CheckBoxPreference switch, CheckBoxPreference checkbox2) {
if (switch.isChecked ()){
checkbox2.setEnabled(false);
} else {
checkbox2.setEnabled(true);
}
}

Maybe a ListPreference is more what you want. From a usability point of view this would make more sense. When you have to choose one selection out of many this would be the most obvious way to do it. See this post for further instructions

Related

Change all views text color in PreferenceActivity programmatically

I want to change text color of all view of PreferenceActivity when a SwitchPreference state changes.
prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:summary="Settings"
android:title="Settings" >
<SwitchPreference
android:key="NightMode"
android:summary="dark and light"
android:title="Night Mode" />
...
</PreferenceCategory>
</PreferenceScreen>
PrefsActivity.java
public class PrefsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean nightMode = sharedPreferences.getBoolean("NightMode", false);
if(nightMode){
//I want to change text color here
}
}
}
I can change backgroundColor of layout this way:
getListView().setBackgroundColor(ContextCompat.getColor(this , R.color.colorBackground));
but how to change text color?
The way to change the text color is to call textviewinstance.setTextColor(color). You'd need to do that to every view independently though.
The best way to do this is to use the android theme system. If you set the theme before calling setContentView, all those views will be created with that theme. Make a theme with the text color you want for nightmode. When nightmode is selected, call recreate() to kill your activity and start a new one, just like what happens on configuration changes. Then in onCreate of the new instance, check if night mode is on and select your theme before setting the content view by calling setTheme(theme).

Setting Preferences Android

I´m having trouble with setting preferences in my app.
In the main layout I have the button to open the settings layout:
Button btnPreferences = (Button) findViewById(R.id.btnPreferences);
btnPreferences.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent("com.absolutkarlos.AppPreferenceActivity");
startActivity(i);
}
});
Then, it open the PreferenceActivity:
public class AppPreferenceActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//--load the preferences from an XML file---
addPreferencesFromResource(R.xml.user_references);
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="True of False"
android:key="checkboxPref" />
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<EditTextPreference
android:summary="Enter a string"
android:defaultValue="#string/food"
android:title="Edit Text"
android:key="editTextPref"
android:name="#string/name"/>
<RingtonePreference
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref"
android:name="Ringtone Preference" />
<PreferenceScreen
android:title="Second Preference Screen"
android:summary=
"Click here to go to the second Preference Screen"
android:key="secondPrefScreenPref" >
<EditTextPreference
android:summary="Enter a string"
android:title="Edit Text (second Screen)"
android:key="secondEditTextPref"
android:name="EditText" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
Everything looks like its going to work ok, but when I test it, don´t save the string I want it to save.
I Mean, I click the setting button, open the setting layout, I write a text on the EditTextPreference call NAME, but it doesn´t save it, instead the LogCat: sendUserActionEvet() mView == null
So, what I´m doing wrong? Did I miss a step? or forgot to add something?
Basically, I just want to user write his name as part of the settings, this name will be shown at the main layout as a big title. The user can write a nickname if he want. It´s just a string that the app must remember always.
Thanks for your help...
As you might have read, the message:
LogCat: sendUserActionEvet() mView == null
can be ignored on S4 devices.
You need read the value of Preference, and change it, for his title, on your AppPreferenceActivity, set onResume method:
#Override
public void onResume(){
super.onResume();
EditTextPreference preference = (EditTextPreference) findPreference("secondEditTextPref");
preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setTitle(newValue.toString());
return true;
}
});
String name = preference.getText();
if(name != null)
preference.setTitle(name);
}
Also, you must remove addPreferencesFromResource method, because is deprecated. You should use onBuildHeaders method. Here you can see an example of PreferenceActivity.

PreferenceEditText to string

So I have EditText in my Preferences and i want to get the text it and use it as String.Then i want to use that string everytime when my button is clicked and it will set my another EditText text to the string from Preference. Codes :
<EditTextPreference android:title="Uredi Text"
android:key="ime"
android:summary="ime pjesme"
/>
Java code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String b1t = preferences.getString("ime", "DEFAULT");
et1 = (EditText) findViewById(R.id.editText1);
//Button Click
public void button(View view) {
et1.setText(b1t);
}
According to the developer docs, you can just use edittextpreference.getText().toString()
http://developer.android.com/reference/android/preference/EditTextPreference.html
I'm not sure where your error is so I'll just give you my code for doing this.
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext();
String string = sharedPreferences
.getString("key", "default");
And in my preferences
<EditTextPreference
android:defaultValue="default"
android:key="key"
android:summary="I'm a summary"
android:title="I'm a title" />
For the onCLick method to modify the edit text
EditText editText = (EditText)
findViewById(R.id.editText);
editText.setText(String.valueOf(string));
This code works. If your application still crashes then your issue is either with your onClick event or something else. I personally prefer onClickListeners for buttons.
Heres the code for an onClickListener.
Button button = (Button)
findViewById(R.id.button);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Do some awesome stuff
}
});
edit: John posted his answer before mine, and his answer reflects most use cases, such as in a standard Activity. My answer is directed solely at the use of a PreferenceActivity.
Here's how you can add Preferences with defaults based on another Preference within a PreferenceActivity. Sorry if there are any errors, I'm typing on my phone.
Your XML-defined Preferences will have their values saved to SharedPreferences automatically, but code-created Preferences will need to be saved/persisted manually.
PreferenceActivity's onConfigurationChange() usually saves the state of code-created preferences (nested PreferenceScreens are a bit strange.)
And, of course, you'll want to do null checks (omitted to save my thumbs.)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Preferences"
android:key="root">
<EditTextPreference android:title="Default Pref Text"
android:key="ime"
android:summary="ime pjesme"
/>
<Preference android:title="Click to add a preference."
android:key="add"
android:summary=""
/>
</PreferenceScreen>
MyActivity.class
public class MyActivity extends PreferenceActivity {
public void onCreate(Bundle inState) {
super.onCreate(inState);
setContentView(R.layout.activity_main);
getPreferenceScreen.findPreference(PREFERENCE_BUTTON).
setOnPreferenceClickListener(new OnNewPrefClickListener());
}
private class OnNewPrefClickListener implements OnPreferenceClickListener {
public boolean onPreferenceClick(Preference preference) {
PreferenceScreen rootScreen = getPreferenceScreen();
EditTextPreference defaultPref =
(EditTextPreference)rootScreen.findPreference("ime");
String defaultText = defaultPref.getText();
EditTextPreference newPref = new EditTextPreference(getApplicationContext());
newPref.setText(defaultText);
rootScreen.addPreference(newPref);
return true;
}
}
}

How to create RadioButton group in preference.xml window?

I'm beginner in Java Android developing. I'm using Eclipse SDK 3.6.1 version. I have a preferences window with two checkbox and one back button.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="PIN requirement">
<CheckBoxPreference
android:title="Use PIN"
android:defaultValue="true"
android:key="checkboxPref" />
<CheckBoxPreference
android:title="Don't use PIN"
android:defaultValue="false"
android:key="checkboxPref2" />
</PreferenceCategory>
<PreferenceCategory>
<Preference
android:title="Back"
android:key="customPref" />
</PreferenceCategory>
</PreferenceScreen>
How to change two CheckBox in to the RadioButton group?
If you need just to enable or disable using PIN, only one CheckBoxPreference will be enough in this case (see example code below, First Category). RadioButtons are usually used, when you need to choose something from a list of settings (ListPreference) - for example (see example code, Second Category), to pick a color.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="First Category">
<CheckBoxPreference
android:title="Using PIN"
android:defaultValue="false"
android:key="checkboxPref"
android:summaryOn="Disable PIN"
android:summaryOff="Enable PIN"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Second Category">
<ListPreference
android:title="Pick your favourite color"
android:key="listPref"
android:defaultValue="4"
android:entries="#array/listArray"
android:entryValues="#array/listValues" />
</PreferenceCategory>
</PreferenceScreen>
The source code for this example will be:
public class PreferencesHelpExample extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String KEY_LIST_PREFERENCE = "listPref";
private ListPreference mListPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Get a reference to the preferences
mListPreference = (ListPreference)getPreferenceScreen().findPreference(KEY_LIST_PREFERENCE);
}
#Override
protected void onResume() {
super.onResume();
// Setup the initial values
mListPreference.setSummary("Current value is " + mListPreference.getEntry().toString());
// 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) {
// Set new summary, when a preference value changes
if (key.equals(KEY_LIST_PREFERENCE)) {
mListPreference.setSummary("Current value is " + mListPreference.getEntry().toString());
}
}
}
For ListPreference you will also need an arrays.xml file, which is located in the "values" folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
<item>red</item>
<item>orange</item>
<item>yellow</item>
<item>green</item>
<item>blue</item>
<item>violet</item>
</string-array>
<string-array name="listValues">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
</string-array>
</resources>
See also some great examples, working with PreferenceActivity - they helped me a lot:
Android Preferences;
How to create a group of RadioButtons instead of a list;
How to display the current value of an Android Preference in the Preference summary?
In some situations, having Preferences behave as radio buttons is a nice feature e.g a simple way of including summary text under each option.
Making a group of checkboxes behave like a group of radio buttons is fairly simple. To do this in Preferences, register all the checkboxes in the group to the same OnPreferenceChangeListener then in this listener use findPreference() to find the other checkboxes and call setChecked(false);
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (key.equals("checkboxPref")) {
//Reset other items
CheckBoxPreference p = (CheckBoxPreference)findPreference("checkboxPref2");
p.setChecked(false);
}
else if (key.equals("checkboxPref2")) {
//Reset other items
CheckBoxPreference p = (CheckBoxPreference)findPreference("checkboxPref");
p.setChecked(false);
}
//Force the current focused checkbox to always stay checked when pressed
//i.e confirms value when newValue is checked (true) and discards newValue
//when newValue is unchecked (false)
return (Boolean)newValue;
}
The only downside is that the checkboxes will not look like radio buttons...
I think this is pretty simple if that is what you want:
Add the checkboxes at the preferenses xml like that:
<CheckBoxPreference
android:key="prefkey_cbp_1"
android:summary="#string/prefkey_cbp_1"
android:title="#string/prefkey_cbp_1"
android:defaultValue="false" />
<CheckBoxPreference
android:key="prefkey_cbp_2"
android:summary="#string/prefkey_cbp_2"
android:title="#string/prefkey_cbp_2"
android:defaultValue="false" />
//etc...
At the preferences class onCreate build an CheckBoxPreference array or list or whatever you like, like that:
ArrayList<CheckBoxPreference> cbp_list = new ArrayList<CheckBoxPreference>();
cbp_list.add((CheckBoxPreference) getPreferenceManager()
.findPreference(PreferencesProtocol.prefkey_cbp_1));
cbp_list.add((CheckBoxPreference) getPreferenceManager()
.findPreference(PreferencesProtocol.prefkey_cbp_2));
Make your preferences class implement OnPreferenceClickListener and set the OnPreferenceClickListener to the checkboxes like that :
for (CheckBoxPreference cbp : cbp_list) {
cbp.setOnPreferenceClickListener(this);
}
Then just override the onPreferenceClick and handle any click. For example if you want checkboxes to perform like radio buttons (in the same radiogroup), meaning, only one checkbox at the time to be check, do something like that:
#Override
public boolean onPreferenceClick(Preference arg0) {
for (CheckBoxPreference cbp : cbp_list) {
if (!cbp.getKey().equals(arg0.getKey()) && cbp.isChecked()) {
cbp.setChecked(false);
}
}
return false;
}
try this:
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, #NonNull Preference preference) {
CheckBoxPreference cb1 = null;
CheckBoxPreference cb2 = null;
ListAdapter adapter = preferenceScreen.getRootAdapter();
for(int i = 0; i < preferenceScreen.getRootAdapter().getCount(); i++)
{
//attention to type and key
Preference pref = (Preference) adapter.getItem(i);
if (pref == null || pref.getKey() == null)
continue;
if (pref.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_akt_position)))
cb1 = (CheckBoxPreference) pref;
if (pref.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_last_location)))
cb2 = (CheckBoxPreference) pref;
if (cb1 != null && cb2 != null)
break;
}
//be safe
if (cb1 == null || cb2 == null)
return super.onPreferenceTreeClick(preferenceScreen, preference);
if (preference.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_akt_position))) {
CheckBoxPreference cb = (CheckBoxPreference) preference;
cb2.setChecked(!cb.isChecked());
}
if (preference.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_last_location))) {
CheckBoxPreference cb = (CheckBoxPreference) preference;
cb1.setChecked(!cb.isChecked());
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}

How to enable a preference in my android application when other preference is disabled?

I have used PreferenceActivity to have preference in my android application. I want one preference say "pref 2" to be enabled when other preference say "pref 1" is NOT checked and "pref 2" to be disabled when "pref 1" is checked.
i.e. exactly opposite of the android:dependancy attribute.
How can I do that?
Yes it's possible to do this out of the box.
Let's say you want to disable pref2 when pref1 is off
Here's the code(preference xml layout) to put in for pref1:
<CheckBoxPreference
android:title="Pref1"
android:key="pref1">
</CheckBoxPreference>
Here's the code(preference xml layout) to put in for pref2:
<EditTextPreference
android:dialogMessage="Pref 2 dialog"
android:title="Pref2"
android:key="pref2"
android:dependency="pref1">
</EditTextPreference>
Like sigmazero13 said, by default disableDependentsState is false so you don't need to include it in the pref1 attributes.
According to the docs here, you can add an attribute to the CheckBoxPreference tag like so:
android:disableDependentsState="true"
By default this is false, which means that the dependents are disabled when the checkbox is unchecked, but by setting it to true, it should have the opposite effect.
I don't think there's any out-of-the-box solution for it, i.e. an inverted dependancy attribute. But there's always the click-listener:
preference1.setOnPreferenceClickListener(pref1_click);
....
private OnPreferenceClickListener pref1_click = new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
preference2.setEnabled(!preference1.isChecked());
return true;
}
}
Android CheckBox??
I am assuming you are using the Android.widget.checkBox:
http://developer.android.com/reference/android/widget/CheckBox.html
Try this
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkbox_id);
if (checkBox1.isChecked()) {
checkBox2.setChecked(false);
}
}
}
GoodLUCK!!

Categories

Resources