Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - difference between res/menu and res/layout?

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?

like image 981
Martin Avatar asked Nov 07 '13 22:11

Martin


1 Answers

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);
    }
}
like image 105
wvdz Avatar answered Sep 27 '22 18:09

wvdz