In a PreferenceFragment
, I have a SwitchPreferenceCompat
added via XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="cat 1">
<SwitchPreferenceCompat
android:key="pref_1"
android:defaultValue="false"
android:title="from xml"/>
</PreferenceCategory>
<PreferenceCategory
android:key="pref_cat_1"
android:title="cat 2"/>
</PreferenceScreen>
and one added programmatically:
PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference("pref_cat_1");
SwitchPreferenceCompat switchPreference = new SwitchPreferenceCompat(getActivity());
switchPreference.setWidgetLayoutResource(android.support.v7.preference.R.layout.preference_widget_switch_compat);
switchPreference.setTitle("programmatically");
switchPreference.setChecked(true);
switchPreference.setDefaultValue(true);
switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(final Preference preference, final Object newValue) {
Toast.makeText(getActivity(), newValue.toString(), Toast.LENGTH_SHORT).show();
return true;
}
});
preferenceGroup.addPreference(switchPreference);
On the screen they look different (fontsize):
I tried omitting the line
switchPreference.setWidgetLayoutResource(android.support.v7.preference.R.layout.preference_widget_switch_compat);
but then the Switch button becomes invisible.
How can I make them look the same?
Test project can be found on Github (branch_two).
When you inflate preferences from XML they use the preferenceTheme
you specified in your app theme.
When you created the preference programmatically you used plain activity theme.
If you use the correctly themed Context it will work as expected:
new SwitchPreferenceCompat(getPreferenceManager().getContext());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With