how to remove this warning - "Element SwitchPreferenceCompat is not allowed here"?

Viewed 5296

In an Android project inside res/xml/ file name pref_visualizer.xml

<?xml version="1.0" encoding="utf-8"?>

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

    <SwitchPreferenceCompat
        android:defaultValue="@bool/pref_show_bass_default"
        android:key="@string/pref_show_bass_key"
        android:summaryOff="@string/pref_show_false"
        android:summaryOn="@string/pref_show_true"
        android:title="@string/pref_show_bass_label" />
    <SwitchPreferenceCompat
        android:key="@string/pref_show_mid_key"
        android:title="@string/pref_show_mid_label"
        android:summaryOff="@string/pref_show_false"
        android:summaryOn="@string/pref_show_true"
        android:defaultValue="@bool/pref_show_bass_default" />
    <SwitchPreferenceCompat
        android:key="@string/pref_show_treble_key"
        android:title="@string/pref_show_treble_label"
        android:summaryOff="@string/pref_show_false"
        android:summaryOn="@string/pref_show_true"
        android:defaultValue="@bool/pref_show_bass_default" />

</PreferenceScreen>

The SwitchPreferenceCompat text is highlighted and says it cant be allowed here.How to fix this warning. The app runs without any problem. But still I would like to know How to fix this issue.

6 Answers

Try to replace PreferenceScreen with android.support.v7.preference.PreferenceScreen in the root tag of your preference XML file (the pref_visualizer.xml in this case).

The "SwitchPreferenceCompat" tag belongs to the com.android.support:preference-v7:28.0.0 library. so you need to match the libraries of the parent "PreferenceScreen" tag and the "SwitchPreference" tag (@f0rrest suggested to update the parent tag to v7). however the instructions and recommendation in the android developer site (developer.android.com/guide/topics/ui/settings) is to use the AndroidX Preference Library. therefore i suggest to migrate the project to AndroidX and use "androidx.preference.PreferenceScreen" for the parent tag.

Your PreferenceScreen's layout cannot be in res/layout/ they have to be in res/xml/

As a supplement to f0rrest's answer for the newer versions, you could also replace PreferenceScreen with androidx.preference.PreferenceScreen which will also work.

Use the full path to the class in the xml to avoid the issue:

<com.example.CustomSwitchPreference..
Related