Demonstrates inflating menus from XML. : Menu « UI « Android






Demonstrates inflating menus from XML.

  
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.apis.app;

import com.example.android.apis.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Demonstrates inflating menus from XML. There are different menu XML resources
 * that the user can choose to inflate. First, select an example resource from
 * the spinner, and then hit the menu button. To choose another, back out of the
 * activity and start over.
 */
public class MenuInflateFromXml extends Activity {
    /**
     * Different example menu resources.
     */
    private static final int sMenuExampleResources[] = {
        R.menu.title_only, R.menu.title_icon, R.menu.submenu, R.menu.groups,
        R.menu.checkable, R.menu.shortcuts, R.menu.order, R.menu.category_order,
        R.menu.visible, R.menu.disabled
    };
    
    /**
     * Names corresponding to the different example menu resources.
     */
    private static final String sMenuExampleNames[] = {
        "Title only", "Title and Icon", "Submenu", "Groups",
        "Checkable", "Shortcuts", "Order", "Category and Order",
        "Visible", "Disabled"
    };
   
    /**
     * Lets the user choose a menu resource.
     */
    private Spinner mSpinner;

    /**
     * Shown as instructions.
     */
    private TextView mInstructionsText;
    
    /**
     * Safe to hold on to this.
     */
    private Menu mMenu;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Create a simple layout
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        
        // Create the spinner to allow the user to choose a menu XML
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, sMenuExampleNames); 
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner = new Spinner(this);
        // When programmatically creating views, make sure to set an ID
        // so it will automatically save its instance state
        mSpinner.setId(R.id.spinner);
        mSpinner.setAdapter(adapter);
        
        // Add the spinner
        layout.addView(mSpinner,
                new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));

        // Create help text
        mInstructionsText = new TextView(this);
        mInstructionsText.setText(getResources().getString(
                R.string.menu_from_xml_instructions_press_menu));
        
        // Add the help, make it look decent
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(10, 10, 10, 10);
        layout.addView(mInstructionsText, lp);
        
        // Set the layout as our content view
        setContentView(layout);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Hold on to this
        mMenu = menu;
        
        // Inflate the currently selected menu XML resource.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(sMenuExampleResources[mSpinner.getSelectedItemPosition()], menu);
        
        // Disable the spinner since we've already created the menu and the user
        // can no longer pick a different menu XML.
        mSpinner.setEnabled(false);
        
        // Change instructions
        mInstructionsText.setText(getResources().getString(
                R.string.menu_from_xml_instructions_go_back));
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // For "Title only": Examples of matching an ID with one assigned in
            //                   the XML
            case R.id.jump:
                Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.dive:
                Toast.makeText(this, "Dive into the water!", Toast.LENGTH_SHORT).show();
                return true;

            // For "Groups": Toggle visibility of grouped menu items with
            //               nongrouped menu items
            case R.id.browser_visibility:
                // The refresh item is part of the browser group
                final boolean shouldShowBrowser = !mMenu.findItem(R.id.refresh).isVisible();
                mMenu.setGroupVisible(R.id.browser, shouldShowBrowser);
                break;
                
            case R.id.email_visibility:
                // The reply item is part of the email group
                final boolean shouldShowEmail = !mMenu.findItem(R.id.reply).isVisible();
                mMenu.setGroupVisible(R.id.email, shouldShowEmail);
                break;
                
            // Generic catch all for all the other menu resources
            default:
                // Don't toast text when a submenu is clicked
                if (!item.hasSubMenu()) {
                    Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
                    return true;
                }
                break;
        }
        
        return false;
    }
    
    

}
//res\menu\category_order.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- This group uses the default category. -->
    <group android:id="@+id/most_used_items">
    
        <item android:id="@+id/last_most_item"
            android:orderInCategory="10"
            android:title="@string/last_most_often" />
    
        <item android:id="@+id/middle_most_item"
            android:orderInCategory="7"
            android:title="@string/middle_most_often" />
    
        <item android:id="@+id/first_most_item"
            android:orderInCategory="4"
            android:title="@string/first_most_often" />
    
    </group>
    
    <!-- This group uses the secondary category, which is used for less oftenly used items.
         Notice these items will show up after the above items.
         (Furthermore, notice how the orders in each category are independent from the other
         category.) -->
    <group android:id="@+id/least_used_items"
        android:menuCategory="secondary">
        
        <item android:id="@+id/last_least_item"
            android:orderInCategory="3"
            android:title="@string/last_least_often" />
    
        <item android:id="@+id/middle_least_item"
            android:orderInCategory="2"
            android:title="@string/middle_least_often" />
    
        <item android:id="@+id/first_least_item"
            android:orderInCategory="0"
            android:title="@string/first_least_often" />
    
    </group>

</menu>



//res\menu\checkable.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Checkable items appear only in submenus or context menus. -->

    <!-- Carefully look at the attribute name checkableBehavior on groups, but
         the attribute name checkable on items. The checkableBehavior encompasses
         the number of items that will be checkable within that group. -->

    <item android:title="None">
        <menu>
            <!-- The none checkableBehavior is default, but we explicitly show it here. -->
            <group android:id="@+id/noncheckable_group"
                    android:checkableBehavior="none">
                <!-- Notice how these items inherit from the group. -->
                <item android:id="@+id/noncheckable_item_1"
                        android:title="@string/item_1" />
                <item android:id="@+id/noncheckable_item_2"
                        android:title="@string/item_2" />
                <item android:id="@+id/noncheckable_item_3"
                        android:title="@string/item_3" />
            </group>
        </menu>
    </item>

    <item android:title="All">
        <menu>
            <group android:id="@+id/checkable_group"
                    android:checkableBehavior="all">
                <!-- Notice how these items inherit from the group. -->
                <item android:id="@+id/checkable_item_1"
                        android:title="@string/item_1" />
                <item android:id="@+id/checkable_item_2"
                        android:title="@string/item_2"
                        android:checked="true" />
                <item android:id="@+id/checkable_item_3"
                        android:title="@string/item_3"
                        android:checked="true" />
            </group>
        </menu>
    </item>

    <item android:title="Single">
        <menu>
            <group android:id="@+id/exclusive_checkable_group"
                    android:checkableBehavior="single">
                <!-- Notice how these items inherit from the group. -->
                <item android:id="@+id/exclusive_checkable_item_1"
                        android:title="@string/item_1" />
                <item android:id="@+id/exclusive_checkable_item_2"
                        android:title="@string/item_2" />
                <item android:id="@+id/exclusive_checkable_item_3"
                        android:title="@string/item_3"
                        android:checked="true" />
            </group>
        </menu>
    </item>

    <item android:title="All without group">
        <menu>
            <!-- Notice how these items have each set. -->
            <item android:id="@+id/nongroup_checkable_item_1"
                    android:title="@string/item_1"
                    android:checkable="true" />
            <item android:id="@+id/nongroup_checkable_item_2"
                    android:title="@string/item_2"
                    android:checkable="true"
                    android:checked="true" />
            <item android:id="@+id/nongroup_checkable_item_3"
                    android:title="@string/item_3"
                    android:checkable="true"
                    android:checked="true" />
        </menu>
    </item>

</menu>



//res\menu\disabled.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/enabled_item"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

    <item android:id="@+id/enabled_item_2"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item_2"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

    <item android:id="@+id/enabled_item_3"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item_3"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

    <item android:id="@+id/enabled_item_4"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item_4"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

</menu>



//res\menu\groups.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/browser_visibility"
        android:title="@string/browser_visibility" />

    <group android:id="@+id/browser">
    
        <item android:id="@+id/refresh"
            android:title="@string/browser_refresh" />
    
        <item android:id="@+id/bookmark"
            android:title="@string/browser_bookmark" />
    
    </group>

    <item android:id="@+id/email_visibility"
        android:title="@string/email_visibility" />

    <group android:id="@+id/email">
    
        <item android:id="@+id/reply"
            android:title="@string/email_reply" />
    
        <item android:id="@+id/forward"
            android:title="@string/email_forward" />
    
    </group>

</menu>



//res\menu\order.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- These are in reverse order in this resource, but the orderInCategory attribute will
         order them for the menu (they all have the same default category). -->

    <item android:id="@+id/fourth_item"
        android:orderInCategory="3"
        android:title="Fourth" />

    <item android:id="@+id/third_item"
        android:orderInCategory="2"
        android:title="Third" />

    <item android:id="@+id/second_item"
        android:orderInCategory="1"
        android:title="Second" />

    <item android:id="@+id/first_item"
        android:orderInCategory="0"
        android:title="First" />

</menu>



//res\menu\shortcuts.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/invisible_item"
        android:visible="false"
        android:alphabeticShortcut="i"
        android:title="Invisible item" />

    <item android:id="@+id/a_item"
        android:alphabeticShortcut="a"
        android:title="Alvin" />

    <item android:id="@+id/b_item"
        android:alphabeticShortcut="b"
        android:title="Bart" />

    <item android:id="@+id/c_item"
        android:alphabeticShortcut="c"
        android:title="Chris" />

    <item android:id="@+id/d_item"
        android:alphabeticShortcut="d"
        android:title="David" />

    <item android:id="@+id/e_item"
        android:alphabeticShortcut="e"
        android:title="Eric" />

    <item android:id="@+id/f_item"
        android:alphabeticShortcut="f"
        android:title="Frank" />

    <item android:id="@+id/g_item"
        android:alphabeticShortcut="g"
        android:title="Gary" />

    <item android:id="@+id/h_item"
        android:alphabeticShortcut="h"
        android:title="Henry" />

    <item android:id="@+id/excl_item"
        android:alphabeticShortcut="!"
        android:title="Exclamation" />

</menu>



//res\menu\submenu.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:title="Normal 1" />

    <item android:id="@+id/submenu"
        android:title="Emotions">

        <menu>        

            <item android:id="@+id/happy"
                android:title="Happy"
                android:icon="@drawable/stat_happy" />
        
            <item android:id="@+id/neutral"
                android:title="Neutral"
                android:icon="@drawable/stat_neutral" />
        
            <item android:id="@+id/sad"
                android:title="Sad"
                android:icon="@drawable/stat_sad" />
        
        </menu>
    
    </item>

    <item android:title="Normal 2" />

</menu>



//res\menu\title_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/happy"
        android:title="Happy"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/neutral"
        android:title="Neutral"
        android:icon="@drawable/stat_neutral" />

    <item android:id="@+id/sad"
        android:title="Sad"
        android:icon="@drawable/stat_sad" />

</menu>



//res\menu\title_only.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/jump"
        android:title="@string/jump" />

    <item android:id="@+id/dive"
        android:title="@string/dive" />

</menu>



//res\menu\visible.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/visible_item"
        android:title="Visible"
        android:alphabeticShortcut="a" />

    <item android:id="@+id/hidden_item"
        android:title="Hidden"
        android:visible="false"
        android:alphabeticShortcut="b" />

    <group android:id="@+id/hidden_group"
        android:visible="false">
    
        <item android:id="@+id/hidden_by_group"
            android:title="Hidden by group"
            android:alphabeticShortcut="c" />
    
    </group>

</menu>

   
    
  








Related examples in the same category

1.Create Option menu
2.Menu and messages
3.Context menu
4.Custom menu
5.Using Icon in Menu
6.Option Menu selection event
7.Menu Inflation
8.Context Menu event
9.Create Menu within your code
10.Activity Menu
11.Define menu in xml file
12.Adding submenu
13.Using Icon in menu and submenu
14.Get Menu title
15.onOptionsItemSelected/onPrepareOptionsMenu/onCreateOptionsMenu Event
16.Basics of the Action Bar and how it interoperates with the standard options menu.
17.Demonstration of displaying a context menu from a fragment.
18.Demonstrates how fragments can participate in the options menu.
19.Usage of SearchView in an ActionBar as a menu item.
20.This demo illustrates the use of CHOICE_MODE_MULTIPLE_MODAL