sisho
sisho

Reputation: 13

Keep view instance in activity or get it everytime?

What's the best practice?

In an activity with a lot of views (hypothetic), should i fill an instance and use it or call the findViewById Everytime?

public class AskActivity extends Activity {
    //this
    public EditText question_edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //...
        //Or this?
        findViewById(R.id.question_edit);
}

Upvotes: 1

Views: 94

Answers (3)

Pier Giorgio Misley
Pier Giorgio Misley

Reputation: 5351

Android studio, fortunatly, is really smart.

First, if you don't use your View outside of the activity, change the property to private (or whatever) instead of public.

Then, as aliaksei said, it depends; there are not best practice.

If you use your view only in one method, create a local variable with

private void myLocalMethod(){
  ...
  View myView = findViewById(R.id.myView);
  ...
}

Elseway, if you use your View in multple methods, create it with class scope:

View myView;

//inside onCreate method, or the first that uses it
...
myView = findViewById(R.id.myView);
// now you can refer to myView anywhere
..

Anyway, if you create a View with class-scope but you reference it only in one method, Android Studio will warn you with something like this:

enter image description here

In any case, don't call findViewById() in every method, if you reference a view in more than one, cast it as class View

Hope this helps!

Upvotes: 2

Anton Malyshev
Anton Malyshev

Reputation: 8861

findViewById is considerably slow call, so yes, store views in variables for future reference as much as possible.

Upvotes: 1

aliaksei
aliaksei

Reputation: 734

They aren't mutually exclusive, you need to do both otherwise if you only do the first one, you will get an NPE anytime you try to use it and similarly with a Inflation Exception for the second one.

Just make sure you actually assign the found view to the EditText variable:

question_edit = (EditText) findViewById(R.id.question_edit);

Upvotes: 0

Related Questions