关注 this tutorial 后为偏好创建一个屏幕,膨胀类“androidx.preference.PreferenceScreen”似乎存在问题。为什么在 res/xml
文件夹中声明了我的首选项并且已将必要的依赖项添加到此项目时找不到它?
我的应用的 minSdkVersion 是 24。
Error inflating class (not found)androidx.preference.PreferenceScreen
依赖项
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 布局
<?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 MySettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, MySettingsFragment())
.commit()
}
}
fragment 类
class MySettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.app_preferences)
}
}
最佳答案
如果你使用的是 AndroidX,你应该更新你的依赖:
implementation "androidx.legacy:legacy-preference-v14:1.0.0"
implementation "androidx.preference:preference:1.0.0"
旧版适用于旧版 com.android.support:preference-v14
,而另一版适用于 com.android.support:preference-v7
。
如果您不使用 AndroidX 而是使用 Android 支持库,请不要将 AndroidX 小部件导入您的 XML。
关于创建首选项屏幕时找不到androidx.preference.PreferenceScreen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53615637/