Выбранный элемент адаптера Kotlin AutoCompleteTextView дает другое значение - PullRequest
0 голосов
/ 05 февраля 2019

Так что я работаю с Kotlin над этим проектом, я в основном использую Java, поэтому я пытаюсь найти эквиваленты в Kotlin для достижения той же функциональности.

Я получаю JSONArray из своей базы данных и храню егов классе данных Serializable, называемом Congregation, он имеет следующие переменные id: Int, name: String, language: String

Теперь у меня есть регистрационное действие, в котором есть вход "Конгрегация", я решил сделать это AutoCompleteTextView, чтобыЯ мог бы предложить возможные значения, совпадающие с тем, что печатали пользователи.Я создал пользовательский ArrayAdapter, и он отлично работает при отображении name Congregation ( изображение ниже)

Emulator showing RegisterActivity.java

Однако , когда я выбираю одно из этих значений, он отображает полный текст значения из списка

например, если я выбираю «Лидс, Кроссгейтс (английский)» вввод будет отображаться Congregation(id=1, name=Leeds, Crossgates, language=English)

Мне интересно, как я могу сохранить значение name для Congregation в поле, когда оно выбрано.

Также, когда я пытаюсь удалить текущее значение поля после выбора элемента, я получаю IndexOutOfBoundsException Index: 1 Size: 1

Настраиваемый адаптер массива (CongregationListAdapter.kt) :

class CongregationListAdapter(context: Activity, resourceId: Int, textView: Int, private var congregations: List<Congregation>)
:ArrayAdapter<Congregation>(context, resourceId, textView, congregations) {

private var inflater: LayoutInflater = context.layoutInflater
private lateinit var view: View

@SuppressLint("SetTextI18n")
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

    if (convertView == null) {
        view = inflater.inflate(R.layout.congregation_list_item, parent, false)
    }
    val name: TextView = view.findViewById(R.id.congregation_text)

    val congregation: Congregation? = getItem(position)
    if (congregation != null) {
        name.text = congregation.name + " (" + congregation.language + ")"
    } else {
        name.text = ""
        return view
    }
    return view
}

override fun getCount(): Int {
    return congregations.size
}

@SuppressLint("SetTextI18n")
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
    if (convertView == null) {
        view = inflater.inflate(R.layout.congregation_list_item, parent, false)
    }
    val congregation: Congregation? = getItem(position)
    val name: TextView = view.findViewById(R.id.congregation_text)
    if (congregation != null) {
        name.text = congregation.name + " (" + congregation.language + ")"
    } else {
        name.text = "Oops. There was a problem"
    }
    return view
}

}

Пользовательское представление (congregation_list_item.xml) :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:orientation="horizontal">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/congregation_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="4dp"
        android:textColor="#000000"
        android:textSize="15sp"
        android:textStyle="normal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints"
        tools:text="Leeds, Crossgates" />

</android.support.constraint.ConstraintLayout>

</LinearLayout>

Конгрегационная модель (Congregation.kt) :

@kotlinx.serialization.Serializable
data class Congregation(
    var id: Int,
    var name: String,
    var language: String
)
...