應用程序可以重寫 onCreateOptionsMenu(Menu menu) 方法創建選項菜單(OptionsMenu), 並重寫 onOptionsItemSelected(MenuItem item) 方法處理事件.
範例:
package com.AndroidMenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class AndroidMenuActivity extends Activity {
final static int OPTION_ID_1 = 1;
final static int OPTION_ID_2 = 2;
final static int OPTION_ID_3 = 3;
final static int OPTION_ID_4 = 4;
final static int OPTION_ID_5 = 5;
/** 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) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
//menu.add(Group, item id, order, title);
menu.add(0, OPTION_ID_1, 0, "Option 1");
menu.add(0, OPTION_ID_2, 1, "Option 2");
menu.add(0, OPTION_ID_3, 2, "Option 3");
menu.add(0, OPTION_ID_4, 3, "Option 4");
menu.add(0, OPTION_ID_5, 4, "Option 5");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case OPTION_ID_1:
Toast.makeText(AndroidMenuActivity.this,
item.getTitle(),
Toast.LENGTH_LONG).show();
break;
case OPTION_ID_2:
Toast.makeText(AndroidMenuActivity.this,
item.getTitle(),
Toast.LENGTH_LONG).show();
break;
case OPTION_ID_3:
Toast.makeText(AndroidMenuActivity.this,
item.getTitle(),
Toast.LENGTH_LONG).show();
break;
case OPTION_ID_4:
Toast.makeText(AndroidMenuActivity.this,
item.getTitle(),
Toast.LENGTH_LONG).show();
break;
case OPTION_ID_5:
Toast.makeText(AndroidMenuActivity.this,
item.getTitle(),
Toast.LENGTH_LONG).show();
break;
}
return true;
}
}
相關文章:
- 子菜單(SubMenu)
沒有留言:
發佈留言