Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 884
Derek Avatar asked Jun 27 '18 16:06

Derek


People also ask

Why is findViewById returning NULL?

FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.

What does findViewById return?

findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .


1 Answers

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"

    }
}
like image 104
egoldx Avatar answered Oct 10 '22 09:10

egoldx