android基礎學習 菜單optionMenu

來源:互聯網
上載者:User

標籤:android   菜單   optionmenu   

1.選項菜單(optionMenu)

    建立選項菜單的步驟:

     1.覆蓋Activity的 onCreateOptionMenu(Menu menu)方法,當菜單第一次被開啟時調用

     2.調用Menu的add() 方法添加功能表項目(MenuItem),同時可以調用MenuItem的setlcon()方法為功能表項目設定表徵圖

     3.當功能表項目(MenuItem)被選擇是,覆蓋Activity 的onOptionsItemSelected(MenuItem item)來響應事件

import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.MenuItem;import android.view.SubMenu;import android.widget.Toast;public class MainActivity extends Activity {private static final int SET_ITEM1=Menu.FIRST+2;private static final int SET_ITEM2=Menu.FIRST+3;private static final int SET_ITEM3=Menu.FIRST+4;private static final int SET_ITEM4=Menu.FIRST+5;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}//填充選項菜單(讀取xml檔案,解析,載入到Menu組件上)@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);  //添加子功能表SubMenu sub1=menu.addSubMenu("設定");sub1.add(1,SET_ITEM1,300,"設定聲音");sub1.add(1,SET_ITEM2,400,"設定案頭");SubMenu sub2=menu.addSubMenu("選擇");sub2.add(1,SET_ITEM3,300,"選擇一");sub2.add(1,SET_ITEM4,400,"選擇二");return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item){switch(item.getItemId()){case R.id.start:Toast.makeText(this, "開始遊戲", Toast.LENGTH_SHORT).show();break;case R.id.over:Toast.makeText(this, "結束遊戲", Toast.LENGTH_SHORT).show();break;case SET_ITEM1:Toast.makeText(this,"聲音設定" , Toast.LENGTH_SHORT).show();break;case SET_ITEM2:Toast.makeText(this, "案頭設定", Toast.LENGTH_SHORT).show();break;case SET_ITEM3:Toast.makeText(this, "選擇一", Toast.LENGTH_SHORT).show();break;case SET_ITEM4:Toast.makeText(this, "選擇二", Toast.LENGTH_SHORT).show();break;default:break;}return super.onOptionsItemSelected(item);}}

在res檔案夾下,values檔案下的Strings.xml 

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">遊戲</string>    <string name="start">開始</string>    <string name="over">結束</string>       <string name="hello_world">你好世界!</string>    <string name="contextTitle">操作功能表</string></resources>


android基礎學習 菜單optionMenu

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.