简体   繁体   English

Android:在SherlockActivity中调用了onOptionsItemSelected(),但在SherlockFragmentActivity中未调用

[英]Android: onOptionsItemSelected() called in SherlockActivity, but not in SherlockFragmentActivity

I have problems with the onOptionsItemSelected() in SherlockFragmentActivity. 我在SherlockFragmentActivity中的onOptionsItemSelected()有问题。 The onCreateOptionsMenu() is called and the option menu is built perfectly, but when I click on an Options item, the onOptionsItemSelected() isn't called. 调用onCreateOptionsMenu()并完美构建选项菜单,但是当我单击选项项目时,不会调用onOptionsItemSelected()。

I tried the same following code in a test Project using SherlockActivity and there it works: 我在一个使用SherlockActivity的测试项目中尝试了相同的以下代码,并且在其中起作用:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

    menu.add(0, 1, 0, "hi").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
    menu.add(0, 1, 0, "ha").setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER | MenuItem.SHOW_AS_ACTION_NEVER);

    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            // Do someting!

        }
        return true;
    }

In both cases, the following imports are done: 在这两种情况下,都完成以下导入:

   import com.actionbarsherlock.app.ActionBar;
   import com.actionbarsherlock.view.Menu;
   import com.actionbarsherlock.view.MenuItem;

Does anyone know help? 有人知道吗? Thank you! 谢谢!

I think that this happens because you don't set MenuItemClickListener (you create items in code). 我认为发生这种情况是因为您没有设置MenuItemClickListener (您在代码中创建了项)。 But if you define menu from xml Android will set listener and fire onOptionsItemSelected on click. 但是,如果您从xml定义菜单, Android将设置侦听器并在单击时触发onOptionsItemSelected。

Thank you! 谢谢! Now I copied the Project and rebuilt my SherlockFragmentActivity and found the problem. 现在,我复制了该项目并重建了SherlockFragmentActivity并发现了问题。 My class already contained public boolean onMenuItemSelected(int featureId, MenuItem item), and this will be called instead of onOptionsItemSelected. 我的课程已经包含公共布尔onMenuItemSelected(int featureId,MenuItem item),它将被代替onOptionsItemSelected调用。 I need this because of the back button at the top left site of an actionbar. 我需要这个是因为操作栏左上角的返回按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM