samedi 22 août 2015

Android: What is best practice for declaring View components in an Activity?

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.

Aucun commentaire:

Enregistrer un commentaire