In this case, if you want to assign a property or listener to your view, there is no difference or disadvantage:
Option 1)
Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener(){ /*código*/ });
Option 2)
findViewById(R.id.button1).setOnclickListener(new View.OnclickListener(){ /*código*/ });
Even using multiple occasions findViewById(R.id.elemento)
does not cause performance problems because you only get the reference of the view in a layout
But what happens if doing option 2, you also need the reference of the view in other parts of your class, in this case you would have to look up the view reference several times using findViewById()
.
For this reason, a variable of the type of view is regularly defined:
private Button button1;
and you get the reference:
button1 = findViewById(R.id.button1);
to be used in other parts of your application.