ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

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, Fragment and View, but you can turn (virtually) any class to an Android Extensions container by implementing the LayoutContainer 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:

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Responses (22)

Write a response