简体   繁体   中英

Kotlin Custom View referencing textview returns null

I have a Custom view:

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"

    }
}

My Layout view_customer looks like this:

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

however when I call it in my other page, the app crashes saying

Caused by: java.lang.IllegalStateException: findViewById(R.id.txtTestName) must not be null at com.helcim.helcimcommercemobile.customviews.CustomerView.(CustomerView.kt:19)

which is when I am trying to assign txtName

I don't really understand how it is null when I have it in the layout view. and it is named the same.

Am I creating a custom view incorrectly?

You have to add parent layout as parameter to 'inflate' method.

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"

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM