end0tknr's kipple - 新web写経開発

http://d.hatena.ne.jp/end0tknr/ から移転します

メニュー入門(写経)

src/MenuTestActivity.java

package jp.end0tknr.menutest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.AlertDialog;

public class MenuTestActivity extends Activity {
	private static final int WASHOKU = 0;
	private static final int KATSUDON = 0;
	private static final int SUKIYAKI = 1;
	private static final int UDON = 2;
	private static final int NIKUJAGA = 3;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	// menu()
    	// http://developer.android.com/reference/android/view/Menu.html#add%28int,%20int,%20int,%20int%29
    	//       GroupId  ItemId    DispOrder  String
    	menu.add(WASHOKU, KATSUDON, Menu.NONE, "カツ丼")
    	.setShortcut('0', 'k');
    	//setShortCut()
    	//you can set numeric and  alpha char shortcat
    	// http://developer.android.com/reference/android/view/MenuItem.html#setShortcut%28char,%20char%29
    	menu.add(WASHOKU, SUKIYAKI, Menu.NONE, "すき焼き")
    	.setShortcut('1', 's');
    	menu.add(WASHOKU, UDON, Menu.NONE, "うどん")
    	.setShortcut('2', 'u');
    	menu.add(WASHOKU, NIKUJAGA, Menu.NONE, "肉じゃが")
    	.setShortcut('3', 'n');
    	//
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getGroupId()) {
    	case WASHOKU:
    		String itemid = Integer.toString(item.getItemId());
    		String title = item.getTitle().toString();
    		showAlertDialog("項目のID = " + itemid + "\n" +
    				"タイトル= " + title);
    		return true;
    	}
    	return super.onOptionsItemSelected(item);
    }

    private void showAlertDialog(String message) {
    	new AlertDialog.Builder(this)
    	.setTitle("選択された項目")
    	.setMessage(message)
    	.setPositiveButton("閉じる", null)
    	.show();
    }
    
}