Mateus Barbosa
Mateus Barbosa

Reputation: 87

How should we set widgets values in Android?

I was looking at my code and I realized that there are at least 3 ways of getting widget's reference in code:

First one (before onCreate):

private TextView textView= (TextView) findViewById(R.id.textView);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
    }

Second one (in onCreate):

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        final TextView textView= (TextView) findViewById(R.id.textView);
     }

Third one (creating out and setting in onCreate):

private TextView textView;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_layout);

            textView= (TextView) findViewById(R.id.textView);
         }

What is the difference between this 3 methods? When should I use them?

Upvotes: 0

Views: 55

Answers (3)

Marcin Orlowski
Marcin Orlowski

Reputation: 75645

You must call setContentView() prior calling findViewById(), therefore on 1st approach will give you null all the times. 2nd and 3rd are the same with the exception for final keyword, but this is Java feature, not Android's.

Upvotes: 1

Shaishav
Shaishav

Reputation: 5312

If you need to call findViewById() then the call should be anywhere after setContentView. Not before that like in your first option. Your third option creates an instance variable, use it only if the textview will be accessed a lot throughout the class, otherwise just call findViewById wherever you need it.

Upvotes: 0

Rafael Carlos
Rafael Carlos

Reputation: 86

The first does not guarantee that your widget is actually instantiated, it is not within the onCreate.

Second will be instantiated, but its value can not be changed because it becomes a constant to be the final.

Third, it is a global variable that will be instantiated in onCreate and you can use it in any other part of your code.

Upvotes: 0

Related Questions