1:在res/menu下面新建main.xml
<span style="font-size:18px;"><menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/option" android:title="@string/menu_setting"> <!-- can add sub menuitem here --> </item> <item android:id="@+id/exit" android:title="@string/menu_exit"> </item> </menu></span>
<span style="font-size:18px;"> </span>
<span style="font-size:18px;background-color: rgb(102, 255, 255);">2:在Activity中加载菜单</span>
<span style="font-size:18px;"> </span><pre name="code" class="java"> /** * 加载菜单 */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; }
3:为菜单添加事件
/** * 为菜单添加事件 */ @Override public boolean onOptionsItemSelected(MenuItem item) { int item_id = item.getItemId(); switch (item_id) { case R.id.option: // do something break; case R.id.exit: // do something super.finish(); default: break; } return true; }
运行效果图:
时间: 2024-10-13 14:29:05