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 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"
}
}