Suppose we have several elements in the MainActivity that require initialization (toolbar, draweLayout, etc.):

 private Toolbar toolbar; private DrawerLayout drawerLayout; private ViewPager viewPager; private FloatingActionButton fab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initToolbar(); initNavigationView(); initTabs(); initFAB(); } private void initToolbar() { ... } private void initNavigationView() { ... } private void initTabs(){ ... } private void initFAB(){ ... } 

How best to make these items available in other Activities? Do I need to redefine the init methods?

    1 answer 1

    All views are attached to the activation. There are exceptions, but in very difficult cases, for example with an overlay, and in this case it does not help.

    You cannot transfer the View from one activity to another, but you can share the initialization code. The easiest option is to bring the code to the base class:

     public class ActivityBase extends Activity { private Toolbar toolbar; private DrawerLayout drawerLayout; private ViewPager viewPager; private FloatingActionButton fab; protected void initContent() { initToolbar(); initNavigationView(); initTabs(); initFAB(); } protected void initToolbar() { ... } protected void initNavigationView() { ... } protected void initTabs(){ ... } protected void initFAB(){ ... } } 

    And in your activities, follow this class:

     public class MyActivity extends ActivityBase { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initContent(); } } 

    Thus, you will not need to write the initialization code of these View in each separate activit, but in all activations there will be different Views not related to the same View in other activites.