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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With