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.
question from:https://stackoverflow.com/questions/65943313/androidx-switchpreferencecompat-on-toolbar