How to call (and use) onOptionsItemSelected from MainActivity in other classes

Yenthe picture Yenthe · Oct 13, 2013 · Viewed 13.4k times · Source

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!

Answer

Kuffs picture Kuffs · Oct 13, 2013

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.