Member-only story
Kotlin Android Extensions: Using View Binding the right way
How to use View Binding in classes other than Activities, Fragments and Views

If you use Kotlin Android Extensions, you’ve probably heard of View Binding feature. “Say goodbye to findViewById” by Antonio Leiva is a very popular article.
The obvious benefit of using View Binding by KTX is it makes your code more concise. You don’t have to use findViewById or the @BindView annotation of ButterKnife library. One less line of code for each view used. Sounds great! But that’s only the Hummock!

I’ll introduce you the Bummock: _$_findCachedViewById
When you use KTX and import your view declared in the xml to your class, the compiler generates a special method for you, that is _$_findCachedViewById. To see that you need to open the Kotlin bytecode and decompile it to Java as described here. I want to dig deeper to point out a common pitfall that is not so obvious.
In the official documentation, it says:
“Android Extensions plugin supports different kinds of containers. The most basic ones are
Activity
,Fragment
andView
, but you can turn (virtually) any class to an Android Extensions container by implementing theLayoutContainer
interface…”
When you use View Binding extensions in a class other than “Activity, Fragment or View” you must implement LayoutContainer interface. That’s not so true. If you pass a view instance to your class, you can simply call your KTX view on the passed instance. If you are in a ViewHolder class, you can directly use itemView:
DONT EVER DO IT!
This prevents the compiler from caching your views. Here is the proof: