2

Why aren't menus inflated automatically for you in Android, the way an Activity's layout is?

Peter vdL
  • 4,953
  • 10
  • 40
  • 60

2 Answers2

4

They are, just override like this:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {     
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.YOUR_MENU_LAYOUT, menu);
        return true;    
    }

EDIT, heres a sample xml, they go in /res/menu

<menu>
   <item android:id="@+id/menu_sample"
          android:title="Sample text"
          android:icon="@drawable/ic_menu_sample"
     />

</menu>
smith324
  • 13,020
  • 9
  • 37
  • 58
  • Here is what I am confused about: The overridden code that you suggest I provide, contains statements that explicitly inflate the XML file. However, my Activity layouts need no such action. So my question is not "how" do I inflate a menu, but "WHY" is this needed? Why aren't menus inflated automatically, like Activity layouts are? Thanks – Peter vdL Aug 28 '10 at 00:42
  • 1
    But the layouts are inflated in the same fashion, just with one API call `setContentView(layout)`. They 'why' part of your question could be as simple as "To make it easier to add sub menus" Take this example. I have an abstract class that extends Activity. It inflates a set of common actions available for the menu options. In the sub classes I use for activities I dynamically add specific options using `addSubMenu(int groupId, int itemId, int order, int titleRes)` This way I don't need to copy and paste xml all over the place. – smith324 Aug 28 '10 at 03:55
3

You do explicitly inflate your activity layout with setContentView(R.layout.whatever). It doesn't have inflate in the name, but that (among a few other things) is what it does.

QRohlf
  • 2,795
  • 3
  • 24
  • 27