androidxmlswitchpreference

SwitchPreference in pre Android 7 always switched off


I'm extending PreferenceFragmentCompat, in the onCreatePreferences method the preference are set using addPreferencesFromResource(R.xml.preferences).

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <SwitchPreference
        android:defaultValue="true"
        android:key="disableAppWhenObscured"
        android:title="@string/screen_settings_block_app_when_obscured" />

</PreferenceScreen>

As dependency I have the following entry:

implementation "androidx.preference:preference-ktx:1.0.0"

On devices post Android 6.X, everything works like expected. On devices with Android 6 and pre-6, the switches are always off and not changeable if clicked on it, even not changeable programmatically but the change listener gets fired.

You know what the problem is?

Edit: If I change the UI element to CheckBoxPreference, everything works as expected even in Android 6 and pre-6. Furthermore before I started using androidX the SwitchPreference worked as well.

Edit2: Found out that the switchView is null inside the SwitchPreference in the following method:

@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
    super.onBindViewHolder(holder);
    View switchView = holder.findViewById(AndroidResources.ANDROID_R_SWITCH_WIDGET);
    syncSwitchView(switchView);
    syncSummaryView(holder);
}

and this leads to not changeing the UI in the syncSwitchView method.


Solution

  • Using SwitchPreferenceCompat instead of SwitchPreference should resolve the problem.