Пользовательский вид Kotlin, ссылающийся на textview, возвращает ноль - PullRequest
0 голосов
/ 27 июня 2018

У меня есть пользовательский вид:

class CustomerView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {

    private var txtName: TextView
    private var txtAge: TextView

    init {

        View.inflate(context, R.layout.view_customer, null)

        txtName = findViewById(R.id.txtTestName)
        txtAge = findViewById(R.id.txtTestAge)

        txtName.text = "Person"
        txtAge.text = "61"

    }
}

Мой макет view_customer выглядит так:

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

    <TextView
        android:id="@+id/txtTestName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="name" />

    <TextView
        android:id="@+id/txtTestAge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="age" />
</LinearLayout>

однако, когда я вызываю его на другой странице, приложение вылетает, говоря:

Причина: java.lang.IllegalStateException: findViewById (R.id.txtTestName) не должен быть нулевым на com.helcim.helcimcommercemobile.customviews.CustomerView. (CustomerView.kt: 19)

когда я пытаюсь присвоить txtName

Я действительно не понимаю, как это нуль, когда у меня есть это в представлении макета. и он назван так же.

Я неправильно создаю пользовательский вид?

1 Ответ

0 голосов
/ 27 июня 2018

Вы должны добавить родительский макет в качестве параметра для метода «inflate».

class CustomerView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {

    private var txtName: TextView
    private var txtAge: TextView

    init {

        View.inflate(context, R.layout.view_customer, this)

        txtName = findViewById(R.id.txtTestName)
        txtAge = findViewById(R.id.txtTestAge)

        txtName.text = "Derek"
        txtAge.text = "23"

    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...