Android開發筆記(9)——初步設定Menu,androidmenu
轉載請註明:http://www.cnblogs.com/igoslly/p/6858656.html 初步設定Menu 設定Menu,在ActionBar上添加按鈕操作: 在main/res目錄下添加menu檔案夾,建立main.xml檔案
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app=" http://schemas.android.com/apk/res/tool"> <item android:id ="@+id/coffee_cart" android:icon="@drawble/cart" android:title="Delete" app:showAsAction=”always”/> </menu>
showAsAction屬性共有五個值:ifRoom、never、always、withText、collapseActionView
ifRoom 會顯示在Item中,依據螢幕的寬窄而定 never 永遠不會顯示。只會在溢出列表中,只顯示標題,所以在定義item的時候,最好把標題都帶上。 always 無論是否溢出,總會顯示。 withText withText值顯示文本標題。如果表徵圖有效且受到空間的限制,文本標題有可能顯示不全。 collapseActionView 被摺疊到一個按鈕中,當使用者選擇時操作視窗展開。一般要配合ifRoom使用才有效果。
在MainActivity中需要改寫onCreateOptionsMenu函數
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; }
設定點擊按鈕函數item.getItemId()擷取點擊按鈕的ID由於對各個item設獨特ID,使用switch-case-default語句判斷,並執行命令
@Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id. coffee_cart: Toast.makeText(this, "CoffeeCart", Toast.LENGTH_SHORT).show(); } }
申明:
1、本筆記為文字及圖片均為個人原創,轉載請註明部落格園-igoslly
2、Android開發課程於2017年4年參與GoogleDeveloper進行學習,筆記原版http://www.studyjamscn.com/thread-20580-1-1.html#pid272486