Search code examples
androidbutterknife

ButterKnife: @BindView but get error saying that button instance variable is not initialized


I am using ButterKnife to bind view element.

Here is my fragment layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    ...

    <Button
        android:id="@+id/ok_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ok" />
</LinearLayout>

My fragment:

class MyFragment : Fragment() {
    @BindView(R.id.ok_btn)
    lateinit var okBtn: Button

    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        okBtn.setOnClickListener { view ->
            Log.d("mytag", "ok clicked!")
        }
    }
}

When I run my simple app, I get error:

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property okBtn has not been initialized
E/AndroidRuntime( 5435):    at com.my.app.MyFragment.onViewCreated(MyFragment.kt:35)

Why I get this error? It sounds like the @BindView(R.id.ok_btn) does't initialize the button instance variable. What do I miss?


Solution

  • where is the line like?

    Butterknife.bind(this, rootView) 
    

    not sure how it should look on Kotlin
    and don't forget to add unbinder
    you should use it with fragments according documentation

    finally it will look something like...

    Unbinder unbinder;
    onViewCreated(){ 
      unbinder = Butterknife.bind(this, rootView); 
      //here you can set your onClickListener
    }
    onDestroyView(){
      unbinder.unbind()
    }
    

    adapt it for Kotlin and bravely use))