Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin's Android Extensions and variables

Tags:

android

kotlin

Before Kotlin, Android developers supposed to save reference to the Activity's Views in a variable like this:

Button fooBtn = (Button) findViewById(R.id.btn_foo)

to reduce the amount of the boiler-plate code and the number of findViewById calls.

With the introduction of the Kotlin's Android Extensions we can reference the same Button by simply using:

btn_foo

Questions:

  1. Does the btn_foo have a reference to the Button saved, or does it call findViewById every time?
  2. Do developers still suppose to use variables to store btn_foo to improve app's performance, or just use it directly in the code?

Edit: there is an explanation how Extensions work, however it is still a bit unclear.

like image 535
0leg Avatar asked Mar 22 '26 08:03

0leg


2 Answers

It's cached, so findViewById isn't called every time you need it. Storing the variable won't definitely improve the app's performance

like image 120
quiro Avatar answered Mar 24 '26 22:03

quiro


One of the Kotlin Android Extension (KAE) developers Ihor Kucherenko confirmed that:

  • KAE will keep a reference to the view after the first call, instead of using findViewById all the time. That works only for Activities and Fragments.

  • KAE will not cache data and will use findViewById every time for any other element (except for an Activity/Fragment).

So in case you are going to init a ViewHolder:

class FooViewHolder(view: View): RecyclerView.ViewHolder(view) {
    fun bind(day: FooItem.Day) {
        btn_foo.text = day.title
    }
}

Decompile into Java call will look like:

((Button)this.itemView.findViewById(R.id.btn_foo)).setText((CharSequence)day.getTitle());

which is exactly what you want to avoid.

The developers might be aware of this.


Conclusion: fill free to use KAE without any additional variables, but only for your Activitiies/Fragments.

like image 35
0leg Avatar answered Mar 24 '26 21:03

0leg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!