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

6

我有一个自定义视图:

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>

然而,当我在其他页面中调用它时,应用程序会崩溃,并显示以下内容:
Caused by: java.lang.IllegalStateException: findViewById(R.id.txtTestName) must not be null at com.helcim.helcimcommercemobile.customviews.CustomerView.(CustomerView.kt:19)
这是在我尝试分配txtName时发生的。我真的不明白为什么它为空,因为我在布局视图中有它,并且名称相同。
我是否错误地创建了自定义视图?

使用从View.inflate返回的视图 | View x = View.inflate() | x.findViewById() - exploitr
1个回答

7
你需要在'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"

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接