Kotlin Android Extensions: Using View Binding the right way

How to use View Binding in classes other than Activities, Fragments and Views

Umut Uz
ProAndroidDev
Published in
3 min readNov 19, 2018

--

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!

Hummock is the top part of the iceberg and Bummock is the bottom part.

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

--

--