Question

I'm an Android newbie, and working on an app which needs an Options menu. I have currently implemented the options menu by setting it as the primary activity and Extending it in the main activity.

But since I work in a team, this method doesn't work always with us since we need to extend another activity which is essential.

My Question How do I implement this Options Menu across the application without Extending the activity in my Main activity?

My Current Setup

  1. I have a MainActivity (This starts first) - MainActivity extends MenuClass
  2. I have the OptionsMenu Class, MenuClass (I want this to be Application wide) - MenuClass extends Activity
  3. I have three other Classes, that extends Activity itself! And these three activities are triggered from the MainActivity and when done, returns to the MainActivity.
Was it helpful?

Solution

If you don't want to, or can't create a base Activity which every other activity then extends - why don't you have a utilities class which has a public static void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {...} function and a public static boolean onOptionsItemSelected(MenuItem item) {...}?

public class Utils {
    public static void onCreateOptionsMenu(Menu menu, MenuInflater inflater ){
        //... create default options here
    }

    public static boolean onOptionsItemSelected(MenuItem item) {
        //... see if you want to handle the selected option here, return true if handled
    }
  }

then from you Activity you can do this:

public class YourActivity extends Activity {

// ...


public void onCreateOptionsMenu(Menu menu, MenuInflater inflater ){
   Utils.onOptionsItemSelected(menu, inflater);
   //... add other options here
}


public boolean onOptionsItemSelected(MenuItem item) {
    boolean handled = Utils.onOptionsItemSelected(item);
    if (!handled) {
        switch(item.getItemId()) {
            case R.id.menu_sign_out:
                //... deal with option
            break;
            //.. deal with other options
        }
    }
    return handled;
}

You may want to change the exact implementation of this depending on how you build it in to your app - ie you may not want the utils methods to be static as you may require some state to be maintained in there, but this should work.

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