Mateus Barbosa Mateus Barbosa - 4 months ago 7
Android Question

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 setting widgets 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?

Answer

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.

Comments