Kotlin 自定义视图引用 textview 返回 null

问题描述 投票:0回答:1

我有一个自定义视图:

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) 不得为 null 在 com.helcim.helcimcommercemobile.customviews.CustomerView。(CustomerView.kt:19)

这是我尝试分配的时候

txtName

当我将它放在布局视图中时,我真的不明白它如何为空。而且它的名字是一样的。

我是否错误地创建了自定义视图?

android android-layout kotlin
1个回答
7
投票

您必须将父布局作为参数添加到“inflate”方法。

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

    private lateinit var txtName: TextView
    private lateinit 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"

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.