androidx SwitchPreferenceCompat on Toolbar - android

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.

Related

inflating class (not found)android.support.v7.preference.PreferenceScreen

hi i have an issue with my app trying to add dark mod light mod option but keep getting this error
android.view.InflateException: Binary XML file line #1: Error inflating class (not found)android.support.v7.preference.PreferenceScreen
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.preference.PreferenceScreen" on path: DexPathList[[zip file "/data/app/~~v5IN-tkiKWj2WITYkTkFBg==/com.example.healthyfood-qVhJKjjdKKHFACt5cLcuZw==/base.apk"],nativeLibraryDirectories=[/data/app/~~v5IN-tkiKWj2WITYkTkFBg==/com.example.healthyfood-qVhJKjjdKKHFACt5cLcuZw==/lib/x86, /system/lib, /system_ext/lib]]
settings activity
public class Settings_activity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener,
androidx.preference.Preference.SummaryProvider<androidx.preference.ListPreference> {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, new SettingsFragment())
.commit();
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null)
supportActionBar.setDisplayHomeAsUpEnabled(true);
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
}
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
String darkModeString = getString(R.string.dark_mode);
if (key != null && sharedPreferences != null)
if (key.equals(darkModeString)) {
final String[] darkModeValues = getResources().getStringArray(R.array.dark_mode_values);
// The apps theme is decided depending upon the saved preferences on app startup
String pref = PreferenceManager.getDefaultSharedPreferences(this)
.getString(getString(R.string.dark_mode), getString(R.string.dark_mode_def_value));
// Comparing to see which preference is selected and applying those theme settings
if (pref.equals(darkModeValues[0]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
if (pref.equals(darkModeValues[1]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
if (pref.equals(darkModeValues[2]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
if (pref.equals(darkModeValues[3]))
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
}
}
#Override
public CharSequence provideSummary(ListPreference preference) {
String key = preference.getKey();
if (key != null)
if (key.equals(getString(R.string.dark_mode)))
return preference.getEntry();
return null;
}
#Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this)
.unregisterOnSharedPreferenceChangeListener(this);
}
}
settings fragments
public class SettingsFragments extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences,rootKey);
}
}
gradle
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.appcompat:appcompat:1.2.0'

SettingActivity by using switchpreferenceCompat

I have a preference screen having multiple SwitchpreferenceCompat. I need to give a user choice of theme change,vibration,etc in settingActivity. Can any one help me in how to set vibrate or theme change by clicking switch in settingactivity. I used this inside my settingActivity fragment but when i click setting activity the app stops
SwitchPreferenceCompat switchPref = findPreference("key");
switchPref.setChecked(true);
`res/xml/root_preference.xml
<SwitchPreferenceCompat
android:id="#+id/vibrate"
app:key="On"
app:title="Vibrate"
android:summaryOff="Off"
android:summaryOn="On"
app:icon="#drawable/ic_baseline_vibration_24"
android:defaultValue="true" />
<SwitchPreferenceCompat
app:key="On"
app:title="Sound"
app:summaryOff="Off"
app:summaryOn="On"
app:icon="#drawable/ic_baseline_volume_up_24"
android:defaultValue="true"/>
</PreferenceCategory>
User clicks the vibration on the app must vibrate when the button is clicked in the activity. How can i do this?
Use Androidx library
implementation 'androidx.preference:preference:1.1.1'
Then create xml folder and add your SwitchPreferenceCompat like below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<SwitchPreferenceCompat
android:id="#+id/vibrate"
android:key="vibrate"
android:summary="It will vibrate your phone"
android:title="Vibrate"/>
<SwitchPreferenceCompat
android:id="#+id/changeTheme"
android:key="theme"
android:title="Change Theme"
android:summary="It will toggle your app theme"/>
</androidx.preference.PreferenceScreen>
Then create SwitchPreferenceCompatActivity like below:
public class SwitchPreferenceCompatActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_preference_compat);
if(savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.preferences_container, new MySettingsFragment())
.commit();
}
}
public static class MySettingsFragment extends PreferenceFragmentCompat {
SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.my_switch_preference_compat, rootKey);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.e("key", key);
if(key.equals("vibrate") && sharedPreferences.getBoolean("vibrate", false)) {
vibratePhone();
}
}
};
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
}
private void vibratePhone() {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
vibrator.vibrate(500);
}
}
}
}
}
Note: add <uses-permission android:name="android.permission.VIBRATE" /> permission on manifest file.

App crashes when changes are made to preferences on resume

I'm having an issue with my preference page crashing my app. On the first visit, it acts as expected. But as soon as I revisit the page and try to change a switch, the app crashes. Here's what the XML looks like for my preferences:
xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory
android:gravity="left"
android:title="#string/description_title"
app:iconSpaceReserved="false">
<SwitchPreference
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:key="#string/pallet_pref_key"
android:title="#string/pallet_pref"
app:iconSpaceReserved="false" />
<SwitchPreference
android:key="#string/nose_pref_key"
android:title="#string/nose_pref"
app:iconSpaceReserved="false" />
<SwitchPreference
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:key="#string/finish_pref_key"
android:title="#string/finish_pref"
app:iconSpaceReserved="false" />
</PreferenceCategory>
</PreferenceScreen>
The Java looks like this:
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import androidx.preference.SwitchPreference;
public class SettingsActivity extends AppCompatActivity {
#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 {
private SharedPreferences sharedPref;
private boolean pNose;
private boolean pPallet;
private boolean pFinish;
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
sharedPref.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
if(s.equals(getResources().getString(R.string.pallet_pref_key))) {
pPallet = sharedPreferences.getBoolean(s,false);
SwitchPreference pNose = findPreference(getResources().getString(R.string.nose_pref_key));
SwitchPreference pFinish = findPreference(getResources().getString(R.string.finish_pref_key));
if (pPallet) {
pNose.setChecked(false);
pFinish.setChecked(false);
}
}
else if(s.equals(getResources().getString(R.string.nose_pref_key))) {
pNose = sharedPreferences.getBoolean(s,false);
SwitchPreference pPallet = findPreference(getResources().getString(R.string.pallet_pref_key));
SwitchPreference pFinish = findPreference(getResources().getString(R.string.finish_pref_key));
if (pNose) {
pPallet.setChecked(false);
pFinish.setChecked(false);
}
}
else if(s.equals(getResources().getString(R.string.finish_pref_key))) {
pFinish = sharedPreferences.getBoolean(s,false);
SwitchPreference pPallet = findPreference(getResources().getString(R.string.pallet_pref_key));
SwitchPreference pNose = findPreference(getResources().getString(R.string.nose_pref_key));
if (pFinish) {
pNose.setChecked(false);
pPallet.setChecked(false);
}
}
}
});
}
}
}
So basically I'm just trying to make it so only one switch can be enabled at a time. I did some research and found a few threads on here that mentioned I should add this code:
#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);
}
I'm thinking that's probably the reason for the crash, but when I add that code below the "OnSharedPreferenceChangeListener() {" statement onResume() and onPause() are greyed out unless I hoist it to the top in which case the this keyword throws an error. Does anyone see what I'm doing wrong?
Here's the error that I get on the crash:

SwitchPreference not working properly - why so?

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();
}
});

OnPreferenceChangeListener dont gets called

I want to change the value of an EditTextPreference when an item in another ListPreference is clicked. But the OnPreferenceChangeListener never gets called.
Heres my code:
public class FragmentPreferences extends PreferenceActivity {
/*#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new UserPreferenceFragment())
.commit();
addPreferencesFromResource(R.xml.userpreferences);
ListPreference listPreference = (ListPreference) findPreference("PREF_MEASURE_UNITS");
if(listPreference.getValue()==null) {
// to ensure we don't get a null value
// set first value by default
listPreference.setValueIndex(0);
}
//listPreference.setSummary(listPreference.getValue().toString());
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//preference.setSummary(newValue.toString());
EditTextPreference EditTextPreference = (EditTextPreference) findPreference("PREF_CAMERA_HEIGHT");
if (newValue.equals(0))
{
EditTextPreference.setText(String.format("%.1f",Float.valueOf(EditTextPreference.getText().replace(',','.'))*2.54f));
}
else if (newValue.equals(1))
EditTextPreference.setText(String.format("%.1f",Float.valueOf(EditTextPreference.getText().replace(',','.'))/2.54f));
return true;
}
});
}
Ive found the solution.
I had to place the code beneath
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new UserPreferenceFragment())
.commit();
in the class
public class UserPreferenceFragment extends PreferenceFragment{
Now its working

Categories

Resources