1)您需要創建(或修改它是否存在)您的菜單資源文件/res/menu/main_menu.xml
以創建操作。
例如:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_refresh"
android:showAsAction="always"
android:icon="@drawable/ic_action_refresh"
android:title="Refresh"/>
<item
android:id="@+id/action_settings"
android:showAsAction="always"
android:icon="@drawable/ic_action_setting"
android:title="Settings">
</item>
</menu>
2)在活動覆蓋onCreateOptionsMenu()
到允許膨脹在XML定義的動作:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
3)重寫onOptionsItemSelected()
反應的操作的選擇:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings:
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
非常感謝!這是一個絕對內容豐富的評論,專門回答了我的問題,並教我關於操作欄。 –