【发布时间】:2020-08-19 14:52:21
【问题描述】:
我想继承 Preference 以在 Kotlin 中创建自定义首选项。我无法在“首选项”屏幕中获取自定义首选项。如果我从我的首选项屏幕中删除此自定义首选项,我已实现的其余首选项(此处未显示)工作正常。 这里有许多类似的看似的问题,但我发现没有一个直接涉及创建自定义首选项的 Kotlin 实现的问题。
请帮助我提供一个您已经测试过的工作示例,它显示了三件事:
custom_preference.xmlCustomPreference.kt-
preference_screen.xml(家长偏好屏幕显示自定义偏好)
这是我的代码:
显示字符串的自定义 xml 首选项(让我们保持简单的示例,尽管我的首选项最终将具有更多功能)
custom_preference.xml
<Preference
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@android:id/widget_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomPreference">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is a custom preference" />
</Preference>
扩展Preference 并包含正确构造函数的类。
CustomPreference.kt
package com.example.myApp
import android.content.Context
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceViewHolder
import android.util.AttributeSet
import com.example.myApp.R
import com.example.myApp.R.layout.custom_preference
class CustomPreference (context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.preferenceStyle,
defStyleRes: Int = defStyleAttr)
: Preference(context, attrs, defStyleAttr, defStyleRes) {
override fun onBindViewHolder(holder: PreferenceViewHolder?) {
super.onBindViewHolder(holder)
layoutResource = custom_preference
}
}
PreferenceScreen 中的自定义首选项声明。
preference_screen.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.example.CustomPreference
app:key="custom_preference_key"
app:title="This is a custom preference" />
</android.support.v7.preference.PreferenceScreen>
注意:我在这里手动重命名了类名作为示例。另外,对于这个项目,我必须使用支持库而不是 Androidx。
【问题讨论】:
标签: android kotlin android-recyclerview android-preferences preferencescreen