Android 中添加menu菜单

龙亮
2023-12-01

menu样式

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/menu_prefs"
        android:title="设置"/>
    <item
        android:id="@+id/menu_quit"
        android:title="退出"/>
</menu>

在activity中复写下面两个方法

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_prefs) {
            Intent intent = new Intent(this, ShareToOtherTest.class);
            startActivityForResult(intent, 0);
        } else if (item.getItemId() == R.id.menu_quit) {
            finish();
        }
        return true;
    }
 类似资料: