Search code examples
androidactionbarsherlockmenuitem

Android: Defining all application menu items in one XML


I am using ActionBarSherlock in my application, and a lot of my menu items are found in many different activities.

Right now I have to define them in each Activity's activity_menu.xml file, so for example

shows in 5 different xml files. Is there a way of defining all my application's menu items once in one xml file, and then for each activity select what menu items I want to show?

EDIT: I read about creating an activity that only implements menu function and then extending it, but this isn't an idle solution for me. Any way of doing what I described?

Hope I was clear, thanks


Solution

  • Yes there is a way, you need not declare in every activity. You need to have something called BaseActivity so that all other activities can be extended from that. Code example:

    BaseActivity.java:

    public class BaseActivity extends SherlockFragmentActivity {
    
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setTheme(Config.THEME);
            // set up action bar
            actionBar = getSupportActionBar();
            // sets device orientation
            setDeviceType(this);
    
            actionBar.setDisplayHomeAsUpEnabled(true);
    
        }
    
    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getSupportMenuInflater();
            inflater.inflate(R.menu.aiwmain, menu);
            return super.onCreateOptionsMenu(menu);
        }
    }
    
    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
    
            super.onOptionsItemSelected(item);
    
            switch (item.getItemId()) {
            case R.id.scanner:
                       //do something on menu click
                    case R.id.location:
               //do something on menu click
            break;
    
            }
    
            return true;
    
        }
    

    Now simply extend your other classes by BaseActivity:

    public class HowToUseActivity extends BaseActivity {
    
    }