移动平台同样有Menu,比如在桌面屏上点击menu按钮,会从底部弹出一个Menu:
同样,我们也可以为自己的Activity定制Menu,主要是覆写onCreateOptionMenu和onOptionsItemsSelected方法:
- public class LayoutActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(new CompoundView(this));
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- super.onCreateOptionsMenu(menu);
-
- int menuId = Menu.FIRST;
- menu.add(0, menuId++, Menu.NONE, "Normal");
- menu.add(0, menuId++, Menu.NONE, "Check box").setCheckable(true);
- int group = 1;
- menu.add(group, menuId++, Menu.NONE, "Radio button one");
- menu.add(group, menuId++, Menu.NONE, "Radio button two");
- menu.add(group, menuId++, Menu.NONE, "Radio button three").setChecked(true);
- menu.setGroupCheckable(group, true, true);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- Toast.makeText(this, item.toString(), Toast.LENGTH_LONG).show();
- return true;
- }
- }
当按键盘上的Menu键时,Menu从下方弹出:
发现check box和radio button和普通的menu item没什么区别。尝试着加入更多的menu item:
发现菜单里多了一个“More“的按钮。点开的话可以显示其余未显示的menu:
除了“options menu“外,还有一种“context menu”,当用户长按方向键的中心键时会弹出。你可以试试调用registerForContextMenu和覆写onCreateContextMenu与onContextMenuItemSelected方法来定制它:
- public class LayoutActivity extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- CompoundView cv = new CompoundView(this);
- setContentView(cv);
- // register for the text view's context menu
- registerForContextMenu(cv.ev);
- }
- @Override
- public void onCreateContextMenu(ContextMenu menu, View v,
- ContextMenuInfo menuInfo) {
- super.onCreateContextMenu(menu, v, menuInfo);
- int menuId = Menu.FIRST;
- menu.add(0, menuId++, Menu.NONE, "Normal");
- }
- }
在layout activity程序运行时,长按方向盘的中心键,显示context menu,可以看到自定义的item:
阅读(1152) | 评论(0) | 转发(0) |