A typical activity in android.
public class MainActivity extends AppCompatActivity {
/* Should I declare view components here? */
TextView textView;
Button button;
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
/* And then create them here */
textView = (TextView) findViewById(R.id.textview);
button = (Button) findViewById(R.id.button);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
/* Or is it better to declare and create them like this? */
Spinner spinner = (Spinner) findViewById(R.id.spinner);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
}
In both cases, the components will work as intended and can be used as intended. However, is there a programming practice or pattern one should follow when declaring views like that in your main activity or fragments? Or does it simply not matter.
It depends on what you write. I'll say a summary about that.
If you declare the views outside onCreate, you will be able to use these views in any method in your activity/fragment.
But if you declare the view in a method like onCreate, you won't be able to reference these views again at all in any other different method. It can only be referenced in that same method you wrote your view declaration in.
However, from my coding experience, I always like to declare them outside onCreate. It has more accessibility, and you won't lose anything.