我想要创建一个自定义偏好项,通过子类化
请帮忙提供一个你已经测试过并且包含以下三个部分的示例代码:
自定义
一个扩展了
注意:此处我手动更改了类名以进行示例。此外,对于此项目,我必须使用支持库而不是Androidx。
Preference
以在Kotlin中实现。但是我无法使得自定义的偏好项在偏好屏幕上加载。如果我从偏好屏幕中删除此自定义偏好项,那么我已经实现的其它偏好项(未在此处显示)都能正常工作。这里有很多看似相似的问题,但是我发现没有一个是直接处理创建自定义偏好项的 Kotlin 实现的问题。请帮忙提供一个你已经测试过并且包含以下三个部分的示例代码:
custom_preference.xml
CustomPreference.kt
preference_screen.xml
(用于显示自定义偏好项的父级偏好屏幕)
自定义
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。
androidx
吗?不过,我需要看看你的代码。 - aminography