android:动态添加到选项菜单

android:动态添加到选项菜单,android,menu,Android,Menu,我只是想将其他活动添加到我的选项菜单中 我的应用程序显示的菜单定义为 public class OptionsMenuTesterActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCre

我只是想将其他活动添加到我的选项菜单中 我的应用程序显示的菜单定义为

public class OptionsMenuTesterActivity extends Activity {
        /** 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) {
            super.onCreateOptionsMenu(menu);

            // Create an Intent that describes the requirements to fulfill, to be included
            // in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE. 
            Intent intent = new Intent(null,getIntent().getData());
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);

            // Search for, and populate the menu with, acceptable offering applications.
            menu.addIntentOptions(
                    Menu.CATEGORY_ALTERNATIVE,  // Menu group 
                 0,      // Unique item ID (none)
                 0,      // Order for the items (none)
                 this.getComponentName(),   // The current Activity name
                 null,   // Specific items to place first (none)
                 intent, // Intent created above that describes our requirements
                 0,      // Additional flags to control items (none)
                 null);  // Array of MenuItems that corrolate to specific items (none)

            return true;
        }
    }
现在我用一个活动创建了另一个简单的应用程序,其androidmaifest如下所示

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.idg.test.dynamicoptionsmenu"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DynamicOptionsMenuTesterActivity"
            android:label="@string/app_name" >
            <intent-filter label="test menu">
                <action android:name="android.intent.action.MAIN" />

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

            </intent-filter>
        </activity>
    </application>

</manifest>

我已经启动了这两个应用程序。但当我点击第一个应用程序的菜单时,我什么也看不到
你能帮我说说我在这里遗漏了什么吗。

这个问题有点老了,但我花了一段时间才完成,所以也许它会为其他人节省一些时间和挫折感。希望对你有帮助

public void openOptionsMenu() { 
    // TODO Auto-generated method stub 
    super.openOptionsMenu(); 
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //call the base class to include system menus
    super.onCreateOptionsMenu(menu);

        int group1 = 1;
        MenuItem bakchome = menu.add(group1,1,1,"title");
        bakchome.setIcon(R.drawable.ic_menu_add);

    return true;
}

@Override 
public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
        case 1:

        Intent intent1 = new Intent(getApplicationContext(), yourintent.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent1);
            break;

        }

    return true;
}
下面是我创建动态菜单的步骤,它提供了共享图像的所有可用选项。我建立了自己的topmenu,而不是使用ActionBar。我的菜单项从
活动的
onCreate
方法中的
ImageButton
开始

    ImageButton shareBtn = (ImageButton)findViewById(R.id.shareBtn);
    shareBtn.setOnClickListener(new View.OnClickListener() {

        // receive launchables (to build menu items)
        List<ResolveInfo> launchables = getLaunchablesToShareWith();
        PackageManager pm=getPackageManager();

        @Override
        public void onClick(View v) {
            //Creating the instance of PopupMenu
            PopupMenu popup = new PopupMenu(getApplicationContext(), v);

            //enable icons using Reflection...
            try {
                Field[] fields = popup.getClass().getDeclaredFields();
                for (Field field : fields) {
                    if ("mPopup".equals(field.getName())) {
                        field.setAccessible(true);
                        Object menuPopupHelper = field.get(popup);
                        Class<?> classPopupHelper = Class.forName(menuPopupHelper
                                .getClass().getName());
                        Method setForceIcons = classPopupHelper.getMethod(
                                "setForceShowIcon", boolean.class);
                        setForceIcons.invoke(menuPopupHelper, true);
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            //Inflating the Popup using xml file
            popup.getMenuInflater().inflate(R.menu.popupmenu_your_activity, popup.getMenu());

            // add items
            for (ListIterator<ResolveInfo> iterator = launchables.listIterator(); iterator.hasNext(); ) {

                // extract data from launchables
                ResolveInfo resolveInfo = iterator.next();
                String title = resolveInfo.activityInfo.applicationInfo.loadLabel(pm).toString();
                String packageName = resolveInfo.activityInfo.applicationInfo.packageName;
                Drawable appIcon = null;
                try {
                    appIcon = pm.getApplicationIcon(packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                    continue;
                }

                // create & add item
                popup.getMenu().add(0, 0, 0, title)
                                .setIcon(appIcon)
                                .setIntent( getShareIntent().setPackage(packageName) )
                                .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                                    public boolean onMenuItemClick(MenuItem item) {
                                        prepareImageToShare(true);
                                        startActivity(item.getIntent());
                                        return true;
                                    }
                                });
            }

            popup.show();
        }
    });
菜单布局文件(popupmenu\u your\u activity.xml)如下所示:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="your.package.YourActivity" >

    <!-- popup menu with dynamic content -->

</menu>

private Intent getShareIntent() {
    // File helper returns something like return Uri.parse("file:///storage/emulated/0/YourApp/output/image.png");
    Uri imageUri = FileHelper.getOutputPathAsUri(Files.SHARED_OUTPUT_FILE.getFilename(), Paths.OUTPUT_FOLDER_PATH.getPath(), true); 

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setData(imageUri);
    shareIntent.setType("image/png");
    shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);

    return shareIntent;
}
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="your.package.YourActivity" >

    <!-- popup menu with dynamic content -->

</menu>