ActionBarSherlock with multiple MenuItems?

不羁的心 提交于 2019-12-05 18:40:09
Ollie C

Create the menu like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

Then use a switch statement to handle selections:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // Do stuff
            return true;
        case R.id.menu_item_2:
            // Do stuff
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

EDIT: Finally, you should do different things for each item, if you change the Intent target Activity to another, it'll do what you expect:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // ... Stuff ...
    case R.id.settings: // Settings item
        Intent i = new Intent(this, About.class); // Start About.java Activity, but item says "settings"
        // TODO: Change About to Settings?
        i = new Intent(this, Settings.class);
        startActivity(i);
        return true;

    case R.id.about: // About item
        Intent about = new Intent(this, About.class); // Start About.java Activty
        startActivity(about);
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

What I find odd is the way you create your menu. You have defined menu layout it in a menu.xml, yet you do not reference this layout in a onCreateOptionMenu() method. It should be something like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

Pay attention to the getSupportMenuInflater() method which is used instead of getMenuInflater(). Why this must be so is somewhere in docemntation about android support library which in term is used by ActionBarSherlock library.

What you do is create menu in code programmatically by using a method menu.add() with a signature add(CharSequence). Nowhere it is in there that you give ItemId. I guess (and this is only a guess) android in that case assigns the same id to all items, something like zero or some other arbitrary number. You should use a method with a signature add(int, int, int,CharSequence) or add(int, int, int, int) as only those allow you to specify ItemId. So, both of your menu items have the same id. And this is (I guess again) the cause that they behave the same. One more thing. Be careful that you use the correct substitute classes and methods from support library and ActionBarSherlock library. Please let us know if this solved the problem as I am only running this in my head.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!