menu.addIntentOptions 添加动态菜单详解
android的一个activity可以再选中某项之后按menu键弹出特定的菜单,也就是动态菜单。动态菜单的实现是靠menu类中的addIntentOptions函数实现的,具体的声明如下:
int android.view.Menu.addIntentOptions(
int groupId,
int itemId,
int order,
ComponentName caller,
Intent[] specifics,
Intent intent,
int flags,
MenuItem[] outSpecificItems)
这个函数是用来动态产生option menu的
函数参数分析:
1. groupid 就是菜单组的编号;
2. itemId (可以让其为0)
3. order 菜单顺序,可以不考虑
4. Caller 就是发起activity的activity
5. Specifics 以action+uri的具体方式来增加激活相应activity的菜单项
6. Intent 以categroy+uri这种一般形式来增加激活相应activity的菜单项
参数Intent和Specifics的区别是,一个用categroy+uri来匹配activity,一个用action+uri来匹配activity。
8. outSpecificItems 这个是返回的MenuItem值,对应以specifics方式匹配的菜单项。
下面以android sdk中notepad的例子来说明其用法。项目所在位置:...\android-sdk-windows\samples\android-8\NotePad
来看这个例子中的NotesList.java文件中的public boolean onPrepareOptionsMenu(Menu menu)函数,这个函数会在设定普通option menu菜单项的的onCreateOptionsMenu函数之后调用,这个函数的主要部分是如下代码:
view plaincopy to clipboardprint?
Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId()); Intent[] specifics = new Intent[1]; specifics[0] = new Intent(Intent.ACTION_EDIT, uri); MenuItem[] items = new MenuItem[1]; Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, null, specifics, intent, 0, items); Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId()); Intent[] specifics = new Intent[1]; specifics[0] = new Intent(Intent.ACTION_EDIT, uri); MenuItem[] items = new MenuItem[1]; Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, null, specifics, intent, 0, items);
<activity android:name="MyAdd" android:label="@string/title_myadd" android:windowSoftInputMode="stateVisible"> <intent-filter android:label="@string/resolve_myadd"> <action android:name="com.android.notepad.action.MYADD" /> <category android:name="android.intent.category.ALTERNATIVE" /> <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> </intent-filter> </activity> <activity android:name="MyAdd" android:label="@string/title_myadd" android:windowSoftInputMode="stateVisible"> <intent-filter android:label="@string/resolve_myadd"> <action android:name="com.android.notepad.action.MYADD" /> <category android:name="android.intent.category.ALTERNATIVE" /> <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> </intent-filter> </activity>
view plaincopy to clipboardprint? Intent[] specifics = new Intent[2]; specifics[0] = new Intent(Intent.ACTION_VIEW, uri); specifics[1] = new Intent("com.android.notepad.action.MYADD",uri); MenuItem[] items = new MenuItem[2]; Intent[] specifics = new Intent[2]; specifics[0] = new Intent(Intent.ACTION_VIEW, uri); specifics[1] = new Intent("com.android.notepad.action.MYADD",uri); MenuItem[] items = new MenuItem[2];