[Android Studio] Section 3 Creating Menu

Table of contents

1. Create a menu


1. Create a menu

The steps to create a menu in Android Studio are as follows:

  1. Open Android Studio and open your Android project.

  2. Under the project's resdirectory, find or create a menudirectory called . This directory is used to store menu resource files.

  3. In menuthe directory, right-click and select "New" -> "Menu resource file". This will open a dialog box for creating a menu resource file.

  4. In the dialog box, enter the name of the menu resource file ( .xmlwith an extension), for example menu_main.xml.

  5. Click the "OK" button, Android Studio will automatically generate a blank menu resource file and open the file in the editor.

    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:id="@+id/item1"
            android:title="菜单项1" />
    
        <item
            android:id="@+id/item2"
            android:title="菜单项2" />
    
        <group android:id="@+id/group">
            <item
                android:id="@+id/subitem1"
                android:title="子菜单项1" />
    
            <item
                android:id="@+id/subitem2"
                android:title="子菜单项2" />
        </group>
    </menu>
    

  6. In the Activity class that needs to display the menu, override onCreateOptionsMenu(Menu menu)the method. Use this method to getMenuInflater().inflate(R.menu.menu_main, menu)parse the menu resource file into a Menu object and add it to the options menu (OptionsMenu).

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    
    switch (id) {
        case R.id.item1:
            // 处理菜单项1的选择事件
            return true;

        case R.id.item2:
            // 处理菜单项2的选择事件
            return true;

        case R.id.subitem1:
            // 处理子菜单项1的选择事件
            return true;

        case R.id.subitem2:
            // 处理子菜单项2的选择事件
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

Through the above steps, you can create a menu in Android Studio and associate it with Activity to realize menu display and click event processing.

Guess you like

Origin blog.csdn.net/AA2534193348/article/details/131444607