I am using Switch Preference in my preference activity to change app theme but it is not working properly . I can't figure out what am i doing wrong here is my code
Here is my prefs.xml
<SwitchPreference
android:defaultValue="false"
android:key="#string/pref_key_dark_mode"
android:title="#string/pref_title_dark_mode"
android:summary="#string/pref_summary_dark_mode"/>
</PreferenceCategory>
and here is my Settings activity
public class SettingsActivity extends AppCompatPreferenceActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// load settings fragment
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainSettingsFragment()).commit();
}
public static class MainSettingsFragment extends PreferenceFragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs_main);
// Stuff to do with night mode switch
final SwitchPreference nightMode = (SwitchPreference) findPreference(getString(R.string.pref_key_dark_mode));
nightMode.setDefaultValue(false);
nightMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (nightMode.isChecked()){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
getActivity().recreate();
nightMode.setChecked(false);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getActivity().recreate();
nightMode.setChecked(true);
}
return false;
}
});
}
}
}
And here is what am i doing in my MainActivity.java
private void setNightMode() {
preferences = getPreferences(MODE_PRIVATE);
if (preferences.getBoolean(getString(R.string.pref_key_dark_mode), true))
{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
I am calling setNightMode(); before on create and onResume
Try This it should help
final SwitchPreference nightMode = (SwitchPreference) findPreference(getString(R.string.pref_key_dark_mode));
nightMode.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if ((Boolean)newValue){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
getActivity().recreate();
}
});
Related
I want to use SwitchPreferenceCompat on toolbar,
How Can I do that?
Thank you very much.
my codes like that:
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
final SwitchPreferenceCompat switchPreference = (SwitchPreferenceCompat) findPreference("sync");
if(switchPreference != null){
switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isOn = (Boolean) newValue;
SwitchPreferenceCompat switchPreference = (SwitchPreferenceCompat) preference;
switchPreference.setChecked(isOn);
return false;
}
});
}
}
}
}
xml/root_preferences.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreferenceCompat
app:key="sync" />
</PreferenceScreen>
Is it possible?
I need your help
Sorry for my bad English.
Thank you very much.
can anyone tell me how can I start/stop a location service (or any other service) when a SwitchPreference in a PreferenceScreen is toggled on/of?
I'm using a settingsFragemnt (extending PreferenceFragemntCompat), which is hosted in my settings activity.
You should add OnPreferenceChangeListener which will allow you to listen switch changes:
final SwitchPreference onOffRandomColor = (SwitchPreference) findPreference(this.getResources()
.getString(R.string.sp_key_on_off_random_color));
onOffRandomColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
if(onOffRandomColor.isChecked()){
}else {
}
return false;
}
});
Next step is to run service:
startService(new Intent(this, LocationService.class));
my fragment looks like this:
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(#Nullable Bundle savedInstanceState, String rootKey){
setPreferencesFromResource(R.xml.prefs, rootKey);
// setting summaries for both list preferences ---------------------------------------------
ListPreference photo_quality = findPreference("photo_quality");
if (photo_quality != null){
photo_quality.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
}
ListPreference uploads = findPreference("upload_options");
if (uploads != null) {
uploads.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
}
// setting the visibility for location service ---------------------------------------------
if (!Auth.getCanDeactiveGps()){
Objects.requireNonNull(getPreferenceScreen()
.findPreference("location_category")).setVisible(false);
}
// handling locationSwitchPreference change ------------------------------------------------
SwitchPreference locationSwitch = findPreference("location");
if (locationSwitch != null){
locationSwitch.setChecked(Settings.getBoolean(Settings.DO_NOT_LOCATE,
false));
locationSwitch.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Settings.setBoolean(Settings.DO_NOT_LOCATE, true);
return false;
}
});
}
}
I'm trying to update my app background color by changing the preferences but the method onSharedPreferenceChanged is never reached. The preferences are changed successfully, but I the listener doesn't work properly:
MainActivity:
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView mRecyclerView;
private ContactsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onResume() {
super.onResume();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettings.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSettings.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, MyPreferenceActivity.class);
startActivity(intent);
return true;
case R.id.action_favorite:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("color")) {
String color = sharedPreferences.getString("color", "3");
int colorId = Integer.valueOf(color);
// Alterar background
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) (findViewById(android.R.id.content))).getChildAt(0);
if (colorId == 1) {
viewGroup.setBackgroundColor(Color.WHITE);
} else if (colorId == 2) {
viewGroup.setBackgroundColor(Color.YELLOW);
} else if (colorId == 3) {
viewGroup.setBackgroundColor(Color.RED);
}
}
}
}
MyPreferenceActivity:
public class MyPreferenceActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
The method onSharedPreferenceChanged is never called, the only way I got it to work was implement the method OnSharedPreferenceChangeListener directly inside the onResume, but sometimes it works fine, sometimes it doesn't and the method is not reached.
The Shared preference registerOnSharedPreferenceChangeListener is valid only when MainActivity is in foreground else that will be unregistered in onPause.
When you are creating a PreferenceActivity named MyPreferenceActivity, the onPause() of MainActivity is called, where the listener is getting unregistered.
One work around could be, unregister from the listener onStop() instead onPause() in MainActivity.
MainActivity.java
#Override
public void onStart() {
super.onStart();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettings.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSettings.unregisterOnSharedPreferenceChangeListener(this);
}
I'm working with my PreferenceActivity where I have a SwitchPreference to which I didn't assing a title using android:title="Title" because I'd like to change it whenever the Switch is clicked.
I've tried this way but didn't work. I also searched on SO related topics without solving my problem.
public class PrefsFragment extends PreferenceFragment {
private SwitchPreference pref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
// Load the preferences from an XML resource
pref = (SwitchPreference)findPreference("SWITCH");
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("SWITCH")) {
boolean test = (Boolean) newValue;
if (test) {
pref.setTitle("ChangedTitle");
} else {
pref.setTitle("DefaultTitle");
}
}
return true;
}
});
}
}
settings.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Settings">
<ListPreference
android:key="yourPref"
android:title="Title"
android:dialogTitle="Select"
android:summary="%s"
android:defaultValue="4"
android:entries="#array/titles"
android:entryValues="#array/values"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Title">
<SwitchPreference
android:key="SWITCH"/>
</PreferenceCategory>
</PreferenceScreen>
Could you help me please?
Try calling preference.setTitle("YOUR TEXT"); within the listener callback, rather than pref.setTitle"YOUR TEXT"); The listener is passing in the preference that was changed.
The problem is with your OnSharedPreferenceChangeListener.
Instead of this,
pref = (SwitchPreference)findPreference("SWITCH");
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("SWITCH")) {
boolean test = (Boolean) newValue;
if (test) {
pref.setTitle("ChangedTitle");
} else {
pref.setTitle("DefaultTitle");
}
}
return true;
}
});
Try this
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if (s.equals("SWITCH")) {
SwitchPreference sp = (SwitchPreference) findPreference(s);
boolean test = sharedPreferences.getBoolean(s, false);
if (test) {
sp.setTitle("ChangedTitle");
} else {
sp.setTitle("DefaultTitle");
}
}
}
}
EDIT: I tried this new code but it still seems they are reset. Can anyone tell me, and propose a solution to my settings being reset?
public class UserSettingActivity extends PreferenceActivity implements OnPreferenceChangeListener{
static SwitchPreference mucus_stamps;
static SwitchPreference fertile_infertil;
static SwitchPreference cervical_mucus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* Populate the activity with the top-level headers.
*/
#Override
public void onBuildHeaders(List<Header> target) {
Log.i("PROJECTCARUSO","onBuildHeaders");
loadHeadersFromResource(R.xml.preference_headers, target);
}
/**
* This fragment shows the preferences for the first header.
*/
public static class Prefs1Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.notification_settings);
}
}
/**
* This fragment shows the preferences for the second header.
*/
public static class Prefs2Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.charting_settings);
//findPreference("cervical_mucus").setOnPreferenceChangeListener(
mucus_stamps = (SwitchPreference) findPreference("mucus_stamps");
fertile_infertil = (SwitchPreference) findPreference("fertile_infertil");
cervical_mucus = (SwitchPreference) findPreference("cervical_mucus");
cervical_mucus.setOnPreferenceChangeListener(
new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// string test w/o "==" usage.
if (newValue.equals(false)) {
Log.i("PROJECTCARUSO","false");
mucus_stamps.setChecked(false);
fertile_infertil.setChecked(false);
} else {
Log.i("PROJECTCARUSO","true");
mucus_stamps.setChecked(true);
fertile_infertil.setChecked(true);
}
// true instead of false so the new value gets kept
return true;
};
});
if(!cervical_mucus.isChecked()){
mucus_stamps.setSelectable(false);
mucus_stamps.setEnabled(false);
fertile_infertil.setSelectable(false);
fertile_infertil.setEnabled(false);
} else {
mucus_stamps.setSelectable(true);
mucus_stamps.setEnabled(true);
fertile_infertil.setSelectable(true);
fertile_infertil.setEnabled(true);
}
}
}
protected void onPause()
{
super.onPause();
}
protected void onResume()
{
super.onResume();
}
#Override
public boolean onPreferenceChange(Preference arg0, Object arg1) {
// TODO Auto-generated method stub
return true;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="#string/pref_chart_profile"
android:textSize="20px">
<SwitchPreference
android:title="#+string/pref_symptothermal"
android:summary="#+string/pref_symptothermal_summary"
android:key="symptothermal"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
<SwitchPreference
android:id="#+id/cervical_mucus"
android:title="#+string/pref_cervical_mucus"
android:summary="#+string/pref_cervical_mucus_summary"
android:key="cervical_mucus"
android:defaultValue="true"
android:layout="#layout/pref_layout" />
<SwitchPreference
android:id="#+id/mucus_stamps"
android:title="#+string/pref_mucus_stamps"
android:summary="#+string/pref_mucus_stamps_summary"
android:key="mucus_stamps"
android:defaultValue="true"
android:layout="#layout/pref_layout" />
<SwitchPreference
android:id="#+id/fertile_infertil"
android:title="#+string/pref_fertile_infertile"
android:summary="#+string/pref_fertile_infertile_summary"
android:key="fertile_infertil"
android:defaultValue="true"
android:layout="#layout/pref_layout" />
</PreferenceCategory>
</PreferenceScreen>
Depending on what you want.
The value is saved(tested), but "selectable" is not a preference value. Therefore you have to set it when the preferencescreen is launched.
Do this:
Before your oncreate:
SwitchPreference mucus_stamps;
Then above your findPreference("mucus_stamps")
mucu_stamps = (SwitchPreference) findPreference("mucus_stamps");
Now, outside the onclicklistener, you can set it.
if(!mucus_stamps.isChecked()){
mucus_stamps.setSelectable(false);
mucus_stamps.setEnabled(false);
}
(I added "setEnablet" to show you that you can disable it aswell, not just make it "non-selectable". Selectable only says that you can't click anything outside the "off/on" area to change it to on/off.)
Personally I prefer to do it like this:
mucus_stamps = (SwitchPreference) findPreference("mucus_stamps");
mucus_stamps.setOnPreferenceChangeListener(
new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
// string test w/o "==" usage.
if (newValue.equals(false)) {
mucus_stamps.setChecked(false);
mucus_stamps.setSelectable(false);
} else {
mucus_stamps.setChecked(true);
}
// true instead of false so the new value gets kept
return true;
};
});
if(!mucus_stamps.isChecked()){
mucus_stamps.setSelectable(false);
mucus_stamps.setEnabled(false);
}
And, you don't need to implement OnPreferenceChangeListener when you do it the way you or I do. Not that it really matters.
:)