Пользовательские настройки Android Kotlin - PullRequest
0 голосов
/ 18 декабря 2018

Я бы хотел создать подкласс Preference для создания пользовательского элемента предпочтений в Kotlin.Я не могу получить пользовательские настройки для раздувания на экране настроек.Если я удалю эту пользовательскую настройку с экрана настроек, остальные настройки, которые я реализовал (здесь не показано), будут работать нормально. Здесь есть много похожих кажущихся вопросов, но ни один из тех, которые я обнаружил, непосредственно не касается проблемы создания пользовательской настройки в Kotlin.

Пожалуйста, помогите мне с рабочим примером , который вы тестировали , который показывает три вещи:

  1. custom_preference.xml
  2. CustomPreference.kt
  3. 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 для этого проекта.

1 Ответ

0 голосов
/ 21 декабря 2018

Попробуйте установить ресурс макета при инициализации класса вместо onBindViewHolder.Также вы должны создать макет, используя обычные элементы виджета (не Preference).

CustomPreference.kt

import android.content.Context
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceViewHolder
import android.util.AttributeSet
import kotlinx.android.synthetic.main.custom_preference_layout.view.*

class CustomPreference @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet,
        defStyleAttr: Int = 0
) : Preference(context, attrs, defStyleAttr) {

    init {
        widgetLayoutResource = R.layout.custom_preference_layout
    }

    override fun onBindViewHolder(holder: PreferenceViewHolder) {
        super.onBindViewHolder(holder)
        with(holder.itemView) {
            // do the view initialization here...

            textView.text = "Another Text"
        }
    }

} 

res / layout / custom_preference_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="This is a custom preference" />

</FrameLayout>

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>
...