6

我最近一直在使用 ActionBarSherlock,并遵循各种教程,我编写了这段代码来将项目添加到操作栏

@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 的点击。

4

3 回答 3

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);
    }
}
于 2012-06-01T13:10:16.513 回答
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);
    }
}
于 2012-06-01T12:17:51.383 回答
0

您可以通过 onOptionsItemSelected 中的 Id 进行 ti ......也可以在此处设置

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.
于 2012-06-01T12:10:58.610 回答