Reputation: 453
I am fairly new to android development, as you probably can tell by my question. I discovered that I have both a res/menu folder and a res/layout folder. They both contain XML files for each activity. But I never used the res/menu folder conciously! I do all of my styling in the res/layout. What do I do in the xml files in res/menu then?
Upvotes: 5
Views: 10403
Reputation: 110
A menu in Android is what is pulled up at the bottom of the screen when the menu bottom is pressed. This menu is created in your activity's class in the onCreateOptionsMenu class:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
As you can see, R.menu.main is being "inflated" in this case. R.menu.main is simply the file named main.xml under your res/menu folder. A sample menu xml file would look something like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_item_1"
android:title="Menu Item">
</item>
</menu>
This xml file produces a menu with one clickable option: Menu Item
An android layout file is used to create the layout of your activity. In a sample onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
setContentView() asks for the id of a layout file. R.layout.main is a file located in res/layout with the name main.xml. This code sets the layout of this activity to whatever is specified in main.xml.
Almost all Android IDEs, including Eclipse, create both a layout and a menu folder by default.
Upvotes: 1
Reputation: 6905
The menu folder, as explicit as its name, is used to store xml
files used for managing menu with xml instead of doing that programmatically.
A simple and good tuto for that
Upvotes: 1
Reputation: 16641
It's intended for use with a menuInflater to create a menu in the onCreateOptionsMenu method of your activity.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
For this example, main.xml could look like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_item_1"
android:title="@string/menu_title2">
</item>
<item
android:id="@+id/menu_item_2"
android:title="@string/menu_title2">
</item>
</menu>
And the action to take when one of the menu items is clicked can be implemented by overriding the onOptionsItemSelected method, perhaps like this:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case (R.id.menu_item_1):
this.startActivity(new Intent(this, MyFirstActivity.class));
return true;
case (R.id.menu_item_2):
this.startActivity(new Intent(this, MySecondActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Upvotes: 8