2011年4月11日 星期一

Menu物件

Menu物件
選單,通常用於修改AP設定使用的物件
簡易的做法
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, ITEM1, 0, "item1");
        menu.add(0, ITEM2, 0, "item2");
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch(item.getItemId()){
            case ITEM1:
                break;
            case ITEM2:
                break;
        }
        return true;
    }

使用resource
在res下新增menu的資料夾,加入xml檔
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
       
<item android:id="@+id/new_game"
                
android:icon="@drawable/ic_new_game"
                
android:title="@string/new_game" />
       
<item android:id="@+id/help"
                 
android:icon="@drawable/ic_help"
                
android:title="@string/help" />
    </menu>

然後在.java加入
    public boolean onCreateOptionsMenu(Menu menu) {
       
MenuInflater inflater = getMenuInflater();
        inflater
.inflate(R.menu.game_menu, menu);
       
return true;
    }


    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
       
case R.id.new_game:
            //newGame
();
           
break;
       
case R.id.help:
            //showHelp
();
           
break;
       
default:
           
return super.onOptionsItemSelected(item);

            break;
       
}

        return true;
    }


其他作法可參照官方網站
Dev Guide - Framework Topics - User Interface - Creating Menus

沒有留言:

張貼留言