Search code examples
androidandroid-activitymultiple-views

Reusing views on multiple activites in Android


I have the following scenario: android up, compatible starting with android 1.6 and up. At the bottom of ALL activities I have a set of ToggleButtons that only start activities. Don't ask me why, that was the request :) Having these buttons do the same thing in all screens I thought like this:

  1. Put the layout in a xml file and it in all my activities layout
  2. Create a class that extends Activity and assign onClick methods for all my buttons
  3. When a ToggleButton is checked, set all other buttons checked="false" and perform the button's operation.

I am stuck on my BaseActivity, when overriding onCreate(). How do I get a hold of my buttons and assign onClick listeners to them ?

public class BaseActivity extends Activity {
    private ToggleButton menuHome;

    @Override
    public void onCreate(Bundle savedInstanceState) {
             //this does not work as it cannot find R.id.menu_home)
        menuHome = (ToggleButton) findViewById(R.id.menu_home);
    }
}

Solution

  • In your other Activities that extend BaseActivity take a look at your OnCreate method. Does it look like this?

    public class YourActivity extends BaseActivity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            base.Oncreate(saveInstanceState);     
    
            setContentView(R.layout.YourLayout);
    
            // Other code here...
        }
    }
    

    It has to do with the order... you haven't set the content view so your toggle button doesn't exist. Try this:

    public class YourActivity extends BaseActivity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            setContentView(R.layout.YourLayout); // Set your content view first.
    
            base.Oncreate(saveInstanceState);     
    
    
    
            // Other code here...
        }
    }