2014年1月25日 星期六

[Android]Menu選單-範例程式

利用onCreateOptionsMenu和onOptionsItemSelected建立選單
可以把application的額外資訊或者額外的功能放在選單裡面
算是還蠻常用的
範例程式原始碼:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//menu.add 參數定義:
 //menu.add (group ID , item_ID, 排列順序, item秀在畫面的名稱);
menu.add(0, 1, 4, "menu_item1");
menu.add(0, 2, 3, "menu_item2");
menu.add(1, 3, 2, "menu_item3");
menu.add(1, 4, 1, "exit");
super.onCreateOptionsMenu(menu);
return true;
}

public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case 1:
//這種寫法可以在指定位置秀出message  
Toast toast1=Toast.makeText(this, "這是第一個item", Toast.LENGTH_LONG);
toast1.setGravity(Gravity.CENTER_HORIZONTAL, 50, 50);
toast1.show();
break;
case 2:
Toast toast2=Toast.makeText(this, "這是第二個item", Toast.LENGTH_SHORT);
toast2.show();
break;
case 3:
Toast.makeText(this, "這是第三個item", Toast.LENGTH_SHORT).show();
break;
case 4:
finish();
break;
}
return true;
}


執行畫面

當然了
隨文附上範例程式下載點
需要的人下載之後匯入Eclipse即可