Android 菜单 使用XML

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.create:
            Toast.makeText(MainActivity.this, "选择了创建文件", 1).show();
            Intent intent = new Intent(MainActivity.this, NextActivity.class);
            item.setIntent(intent); /* 切换到第二个Activity */
            break;
        case R.id.open:
            Toast.makeText(MainActivity.this, "选择了打开文件", 1).show();
            break;
        case R.id.load:
            Toast.makeText(MainActivity.this, "选择了加载文件", 1).show();
            break;
        case R.id.save:
            Toast.makeText(MainActivity.this, "选择了保存文件", 1).show();
            break;
        default:
            break;
        }

        return super.onOptionsItemSelected(item);
    }
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:icon="@drawable/a1"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="主菜单">
        <menu>
            <item
                android:id="@+id/create"
                android:title="新建文件"/>
            <item
                android:id="@+id/open"
                android:title="打开文件"/>
        </menu>
    </item>
    <item
        android:id="@+id/action_user"
        android:icon="@drawable/a1"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="用户菜单">
        <menu>
            <item
                android:id="@+id/load"
                android:title="加载文件"/>
            <item
                android:id="@+id/save"
                android:title="保存文件"/>
        </menu>
    </item>

</menu>

image

image

image

菜单显示到导航栏

android:showAsAction="ifRoom"
image
posted @ 2019-11-03 17:11  thomas_blog  阅读(440)  评论(0编辑  收藏  举报