`
cloudtech
  • 浏览: 4611726 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

Android中的Menu

 
阅读更多

OptionMenu--点击menu按钮式显现

onCreateOptionMenu(Menu menu)--当菜单第一次被打开时调用
onPrepareOptionsMenu(Menu menu)--菜单每次打开都会触发该方法
两种方法都是传入Menu对象,我们可以通过配置该对象来构建合适的OptionMenu

onOptionsItemSelected(MenuItem item)--当Optionmenu被点击的时候触发


ContextMenu
与OptionMenu不同,想要为某个视图指定context menu,需要调用registerForContextMenu(view)方法,为该view注册监听器
ContextMenu的创建是通过long press事件触发的
事件发生时会调用Activity容器的 onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) 方法
方法参数
menu:通过该参数来构造contextmenu信息
v:被点击的试图
menuInfo:被点击视图的信息
ContextMenu一般构建在ListView上一起使用,ListView继承至AdapterView
AdapterView的chidren视图都是通过Adapter类来提供的,当AdapterView的chidren视图的long press事件被触发时
在回调函数里:1,通过对应的Adapter类来获取被点击chidren视图的信息(row,position,视图对象等等)
2,将这些信息封装到AdapterView.AdapterContextMenuInfo这个类中去
long press事件会触发创建ContextMenu从而调用Activity容器的onCreateContextMenu()方法
而步骤2中的AdapterContextMenuInfo对象将最为参数传入到onCreateContextMenu()方法中去

当contextMenu被点击时,调用onContextItemSelected()方法进行回调处理

在对menu信息进行构建时我们可以采用两种方法
1,编码方式添加菜单--menu.add(int groupId,int menuItemId,int order,String title)
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
2,加载menu的xml配置文件--通过MenuInflater
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);


同样还可以构建subMenu,调用Menu的addSubMenu()方法,该方法会返回一个SubMenu对象
可以通过SubMenu的add方法添加子菜单,subMenu的回调处理方法与其parentMenu的回调方法相同
即:如果是OptionMenu调用onOptionsItemSelected,如果是contextMenu调用onContextItemSelected()


menu对象的一个比较有用的方法addIntentOptions()
如果一个menu的menuItem比较明确,即我们知道应该为menu指定哪些menuItem时,可以使用menu.add()方法
然而如果一个menu的menuItem数据是不可预知的,需要根据具体的情况来判断,menu.add()方法便不能满足,
这是可以使用menu.addIntentOptions()方法.
由方法名可以猜到为menu所指定的menuItem是通过一个Intent来决定的,对该intent对象也有要求
其category属性为Intent.ALTERNATIVE_CATEGORY and/or Intent.SELECTED_ALTERNATIVE
如果某个组件的intent-filter匹配该intent,那么menu将会添加一个menuItem来作为该组件的链接
itent-filter的lable属性将作为menuItem的title
方法参数如下:
menu.addIntentOptions(
0, // group ID --int
0, // Unique item ID (none)--int
0, // Order for the items (none)--int
this.getComponentName(), // The current Activity name--ComponentName
null, // Specific items to place first (none)--Intent[]
intent, // Intent created above that describes our requirements--intent
0, // Additional flags to control items (none)--int
null); // Array of MenuItems that corrolate to specific items (none)--MenuItem[]
)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics