After following this tutorial to create a screen for preferences, there seems to be a problem with inflating the class 'androidx.preference.PreferenceScreen'. Why is it not found when my preferences have been declared inside the res/xml
folder and the necessary dependency has been added to this project?
My app's minSdkVersion is 24.
Error inflating class (not found)androidx.preference.PreferenceScreen
dependencies
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:preference-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="preference_a"
android:defaultValue="false"
android:title="Preference A" />
</androidx.preference.PreferenceScreen>
Activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/settings_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MySettingsActivity" />
Activity class
class MySettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, MySettingsFragment())
.commit()
}
}
Fragment class
class MySettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.app_preferences)
}
}
If you're using AndroidX, you should update your dependencies:
implementation "androidx.legacy:legacy-preference-v14:1.0.0"
implementation "androidx.preference:preference:1.0.0"
The legacy is for the old com.android.support:preference-v14
while the other is for com.android.support:preference-v7
.
If you don't use AndroidX but Android Support libraries, do not import AndroidX widgets into your XML.
if you want to use PreferenceFragmentCompat
first you need to implement the following dependency in you app level gradle.
implementation 'androidx.preference:preference:1.0.0
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