Question

I'm making my very first Android application but I ran into a problem. I have over 8 different classes which all use the same actionbar. Now in place of calling the method in every different class (and having a lot of double code) I would like to call the method of the main class in my other classes.

This is a part of my code for the onOptionsItemSelected in main.java

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
        case R.id.actionbar_new_income:
            Intent newIncome = new Intent(this, NewIncome.class);
            this.startActivity(newIncome);
            return true;
} 
}

Now I was wondering how I could call the method in another class (newIncome.java) I have this so far, but it keeps saying I need to add arguments. And I ofcourse need to be able to detect which menuitem is clicked..

MainActivity main = new MainActivity();
        main.onOptionsItemSelected();

Any help please? Thanks!

Was it helpful?

Solution

You should not do this. If you have common code then put it in a class (not an activity) that is accessible by any activity that needs it.

You will still have some duplication but this is normal.

A good way of reducing activity launch code is to add a static method to each activity that you can call which launches the activity it is in.

E.g in your NewIncome Activity you could have

Public static void Launch(Context c) {
    Intent newIncome = new Intent(c, NewIncome.class);
    C.startActivity(newIncome);  
}

You could then launch this activity from any other activity just by calling

NewIncome.Launch(this);

If required you can add parameters to the method and then add Extras to the Activity using these parameters.

OTHER TIPS

You can do it like the following example if your menu entries are totally independent of the activity in which they are contained:

In each activity

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  return CommonClass.HandleMenu(this, item.getItemId());
}

In a common class

public class CommonClass {

    public boolean HandleMenu (Context c, int MenuEntry) {
        switch (MenuEntry) {
           case R.id.actionbar_new_income:
             NewIncome.Launch(c);
          etc....
          ...
    }


}

If your 8 classes are activities you may define a base activity with the onOptionsItemSelected which is the one where you put the elements in the actionbar you want. Then make the other activities derive from it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top