如何区分ActionBarSherlock中的两个菜单项单击?

时间:2012-06-01 12:06:59

标签: android actionbarsherlock android-actionbar

我最近一直在使用ActionBarSherlock,并且在编写各种教程之后,我编写了这段代码来向Action栏添加项目

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    menu.add("Refresh")
        .setIcon(R.drawable.ic_action_refresh)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);


    menu.add("Search")// Search
        .setIcon(R.drawable.ic_action_search)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
}

但是,我不知道如何区分两次点击。

虽然我确实发现你必须覆盖onOptionsItemSelected来处理点击,并且还可以使用switch语句来区分点击次数,但是大多数教程都使用来自xml菜单的项ID。由于我没有在xml中创建菜单,如何在没有ID的情况下区分点击次数。

3 个答案:

答案 0 :(得分:17)

private static final int REFRESH = 1;
private static final int SEARCH = 2;

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    menu.add(0, REFRESH, 0, "Refresh")
        .setIcon(R.drawable.ic_action_refresh)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);


    menu.add(0, SEARCH, 0, "Search")
        .setIcon(R.drawable.ic_action_search)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case REFRESH:
            // Do refresh
            return true;
        case SEARCH:
            // Do search
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

答案 1 :(得分:1)

请检查以下

http://developer.android.com/guide/topics/ui/actionbar.html

包含

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {   <--- here you can get it
        case android.R.id.home:
            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

答案 2 :(得分:0)

你可以通过onOptionsItemSelected ................中的Id来做,也可以在这里设置

http://thedevelopersinfo.wordpress.com/2009/10/29/handling-options-menu-item-selections-in-android/

http://developer.android.com/reference/android/view/Menu.html#add(int,int,int,java.lang.CharSequence)

use 
public abstract MenuItem add (int groupId, int itemId, int order, CharSequence title)

Since: API Level 1
Add a new item to the menu. This item displays the given title for its label.
Parameters

groupId The group identifier that this item should be part of. This can be used to define groups of items for batch state changes. Normally use NONE if an item should not be in a group.
itemId  Unique item ID. Use NONE if you do not need a unique ID.
order   The order for the item. Use NONE if you do not care about the order. See getOrder().
title   The text to display for the item.
Returns

The newly added menu item.