Kotlin Android Extensions and Variables

Before Kotlin, Android developers have to store the Activity Views reference in a variable like this:

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

      

to reduce the number of boiler room code and the number of calls findViewById

.

With the introduction of the Kotlin Android Extensions, we can reference the same button simply by using:

btn_foo

      


Questions:

  • Is there a link btn_foo

    to link to the saved button or is it calling findViewById

    every time?
  • Are developers still using storage variables to btn_foo

    improve application performance, or are they just using it directly in their code?

Edit: There is clarification on how extensions work, however this is still a little unclear.

+3


source to share


2 answers


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

  • KAE will keep the link to the view after the first call, instead of being used findViewById

    all the time. This only works for Activities

    and Fragments

    .

  • KAE will not cache data and will use it findViewById

    every time for any other element (except Activity

    / Fragment

    ).

So, if you are going to initialize ViewHolder

:

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

      

Decompile the Java call would look like:



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

      

what exactly do you want to avoid.

Developers may be aware of this.


Conclusion : fill in the KAE without any additional variables, but only for your Activitiies

/ Fragments

.

+4


source


It is cached so findViewById

it is not called every time you need it. Storing a variable will definitely not improve application performance



+5


source







All Articles