Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwitchPreferenceCompat looking different when added to XML vs created programmatically [duplicate]

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):

enter image description here

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).

like image 553
fweigl Avatar asked Mar 22 '17 15:03

fweigl


1 Answers

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());
like image 111
Eugen Pechanec Avatar answered Oct 09 '22 11:10

Eugen Pechanec