Use directly findViewById ()

2

Are there performance or other disadvantages when using findViewById() directly without an object?

I mean, instead of:

Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener(){ /*código*/ });

Use only:

findViewById(R.id.button1).setOnclickListener(new View.OnclickListener(){ /*código*/ });
    
asked by felipe 01.01.2018 в 22:13
source

3 answers

1

There are no problems in my opinion, but I would recommend using it from the variable created, since you are storing the reference of the button that would make it easier in case you require it to implement other events such as onKey() , onLongClick() , onKeyDown() etc, without having to re-invoke it by findViewById.

Greetings.

    
answered by 02.01.2018 в 19:57
0

There are no such marked disadvantages to add% anonymous% co (in my opinion) , the first option is simply to have a reference to said OnClickListener for later if you want to manipulate or perform any other action with this element you can access.

The question that comes to mind would be, and do you want to work with that button to manipulate your text or something else? , Yes. Sure you must do View again. there is the disadvantage.

In the end the first option is only a variable concept, which is used to store a reference to a findViewById .

    
answered by 01.01.2018 в 22:30
-1

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.

    
answered by 12.01.2018 в 01:51