ButterKnife:@BindView 但出现错误,提示未初始化按钮实例变量

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

我正在使用 ButterKnife 绑定视图元素。

这是我的片段布局:

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

我的片段:

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

当我 运行 我的简单应用程序时,出现错误:

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

为什么会出现这个错误?听起来 @BindView(R.id.ok_btn) 没有初始化按钮实例变量。我想念什么?

这条线在哪里?

Butterknife.bind(this, rootView) 

不确定它在 Kotlin 上的表现如何
并且不要忘记添加 unbinder
你应该根据 documentation

将它与片段一起使用

最终它看起来像...

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

为 Kotlin 改编并勇敢地使用它))