onCreateOptionsMenu is never called

后端 未结 11 1038
有刺的猬
有刺的猬 2020-12-13 03:13

I am having some trouble getting an options menu working in Android. I have built apps before, and they all worked fine, but now the menu just doesn\'t pop up.

The c

相关标签:
11条回答
  • 2020-12-13 04:08

    In the method: Fragment#onCreateView(...) you should put:

    setHasOptionsMenu(true);
    

    Then your method will be called.

    0 讨论(0)
  • 2020-12-13 04:12

    I had a similar issue, but a different solution I am sharing with the community (as it took me one hour to understand what was happening):

        abstract class BaseActivity : AppCompatActivity{
          override fun onCreate(savedInstanceState: Bundle?) {
          setSupportActionBar(my_toolbar)
          }
        }
        class MyActivity : BaseActivity{
            // TODO : some good stuff
        }
    

    where my_toolbar is an object created in my xml file through dataBinding.

    The issue looks the same, no toolbar appear, no call to onCreateOptionsMenu.

    My solution was to promote this code to the child class and not to that basic, as my_toolbar is only initialized as the child class is built.

    0 讨论(0)
  • 2020-12-13 04:16

    Maybe you also have overrode onKeyDown method and made it always return true. Returning true means that keyEvent will be prevented from being propagated further. See code below:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
            /*
              handling event
             */
            return true; //onCreateOptionsMenu won't be invoked.
    }
    
    0 讨论(0)
  • 2020-12-13 04:20

    I was having the same problem (menu not showing up, onCreateOptionsMenu not being called).

    If you are calling this within a fragment, you need to override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) not public boolean onCreateOptionsMenu(Menu menu). Fragments do not use the latter, so they will never even call it.

    Activity menu

    Fragment menu

    0 讨论(0)
  • 2020-12-13 04:20

    Try This It works for me:---

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.home_page_menu, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        switch (item.getItemId()) {
        case R.id.menu_delete:
            Toast.makeText(this, "You pressed the Delete!",
                     Toast.LENGTH_LONG).show();
            break;
    
    
          case R.id.menu_setting:
         Intent intent=new Intent(HomePage.this,Setting.class);
         startActivity(intent);
         finish();
         Toast.makeText(this, "You pressed the Setting!",
         Toast.LENGTH_LONG).show(); break;
    
    
        }
    
        return super.onOptionsItemSelected(item);
    }
    
    0 讨论(0)
提交回复
热议问题