首页 > 解决方案 > How to check if binder of Butterknife is unbinded

问题描述

Sometimes I got exception: kotlin.UninitializedPropertyAccessExceptionlateinit property textTv has not been initialized

declaration of view:

@BindView(R.id.tv) internal lateinit var textTv: RipplePulseLayout

rest are classic ButterKnife init:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    // bind view using butter knife
    unbinder = ButterKnife.bind(this, rootView);
    textTv.postDelayed({
         //do impl here
    }, 500)
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
}

After tracking the issue I found that when using widget in separated thread like postDelayed

Traditional approach to make textTv nullable .. I wonder if there is better solution. I tried removeCallback of textTv in onDestroyView. It did not work with me

标签: androidkotlinbutterknifepostdelayed

解决方案


I found there is a nice way to set unbinder to Unbinder.EMPTY

override fun onDestroyView() {
    super.onDestroyView()
    unbinder.unbind()
    unbinder = Unbinder.EMPTY
}

and check that inside runnable:

textTv.postDelayed({
    if(unbinder == Unbinder.EMPTY) {
         //do impl here
    }
}, 500)

推荐阅读