安卓动态菜单

来源:互联网 发布:oauth独立域名 编辑:程序博客网 时间:2024/04/28 17:30

英文原文:http://developer.android.com/guide/topics/ui/menus.html?#intents

根据传入Intent对象添加Menu组件


在一些情况下,你需要通过菜单组件,使用intent来启动一个activity(无论这个activity在否当前应用中)。当你知道这个你使用的intent的详情和准备好一个菜单组件来启动这个intent的时候,你可以在这个组件所对应的选择回调函数(例如onOptionsItemSelected())中执行以这个intent为参数的startActivity()方法。

但是,当本机内没有一个应用程序能够处理这个intent,你创建的这个发送这个intent的菜单控件会最终无效,因为没有一个activity能够与这个intent对应。为了解决这个问题,Android系统提供了下面一种机制,使得只有在Android能够在本地找到能够处理这个intentactivity时候,才动态地添加这个菜单组件。

添加动态菜单组件的步骤如下:

1、定义一个种类为CATEGORY_ALTERNATIVE或者CATEGORY_SELECTED_ALTERNATIVE和其他需要使用的属性的intent对象

2、调用Menu.addIntentOptions()Android系统会首先在本地查找能够处理这个intentactivity,如果能够找到则Android系统自动添加这个组件到菜单中,否则不添加。

注意:因为CATEGORY_SELECTED_ALTERNATIVE是用来已经在界面中选择条目的intent的。所以,这个类型属性只能用在onCreateContextMenu()方法中。

例如:

@Override

publicboolean onCreateOptionsMenu(Menu menu){

super.onCreateOptionsMenu(menu);

// Createan Intent that describes the requirements to fulfill, to be included

// in ourmenu. The offering app must include a category value ofIntent.CATEGORY_ALTERNATIVE.

Intent intent=newIntent(null, dataUri);

intent.addCategory(Intent.CATEGORY_ALTERNATIVE);

// Searchand populate the menu with acceptable offering applications.

menu.addIntentOptions(

R.id.intent_group,// Menugroup to which new items will be added

0,// Uniqueitem ID (none)

0,// Orderfor the items (none)

this.getComponentName(),// Thecurrent activity name

null,// Specificitems to place first (none)

intent,// Intent created above thatdescribes our requirements

0,//Additional flags to control items (none)

null);// Array ofMenuItems that correlate to specific items (none)

returntrue;

}

对于每一个android系统中找到的符合要求的activity,都会一个与之对应的菜单组件创建,并且使用这个activity中能够对应得上这个intentintent filterandroid:label作为这个菜单组件的标题和这个activity的应用程序的图标作为图标。addIntentOptions()将成功创建的菜单组件总数作为返回值。

Note: When you calladdIntentOptions(), it overrides any and all menu items by themenu group specified in the first argument.

让你的activity能够添加到其他应用程序的菜单中

为了达到标题中的目的,你的activity必须要在intent filter中的类型属性使用下面的两个值之一:CATEGORY_ALTERNATIVE或者CATEGORY_SELECTED_ALTERNATIVE

例子:

<intent-filterlabel="@string/resize_image">

...

<categoryandroid:name="android.intent.category.ALTERNATIVE"/>

<categoryandroid:name="android.intent.category.SELECTED_ALTERNATIVE"/>

...

</intent-filter>