Okay, so - I want to add Preference Settings to my app, in which the user can switch between dark and white mode of the app. The problem is there are only tutorials for Android and there are no for AndroidX. I am new to app-making and I cannot make it work. Here is my Java class:
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreference;
public class SettingsActivity extends AppCompatActivity {
private SwitchPreference darkModeSwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
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);
SwitchPreference darkModeSwitch = (SwitchPreference) findPreference("darkmode");
assert darkModeSwitch != null;
darkModeSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
return false;
}
});
}
}
}
This is my root_preferences.xml file:
<PreferenceCategory
app:title="General">
<SwitchPreferenceCompat
app:key="darkmode"
app:title="Dark mode"/>
</PreferenceCategory>
The activity is not manually made, it is the general SettingsActivity in Android Studio. Every help is appreciated.
This is the error I receive, caused in the setOnPreferenciesChangeListener()
:
java.lang.ClassCastException: androidx.preference.SwitchPreferenceCompat cannot be cast to androidx.preference.SwitchPreference
java.lang.ClassCastException: androidx.preference.SwitchPreferenceCompat cannot be cast to androidx.preference.SwitchPreference
ClassCastException
is a runtime exception raised in Java when we try to improperly cast a class from one type to another.
You should set SwitchPreference
<PreferenceCategory
app:title="General">
<SwitchPreference
app:key="darkmode"
app:title="Dark mode"/>
</PreferenceCategory>
Or use
SwitchPreferenceCompat darkModeSwitch = (SwitchPreferenceCompat) findPreference("darkmode");