Implementing an option menu in Android Studio

后端 未结 4 1658
名媛妹妹
名媛妹妹 2021-02-14 02:02

How do I implement an option menu in my android application? I tried code from Android Developer but I get errors. Such as these: Element menu must be declared.

4条回答
  •  长情又很酷
    2021-02-14 02:08

    You need to create a menu.xml in directory res->menu like menu

    
    
    
    
    

    Then you need to create your menu from activity with below code

     @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        int id = item.getItemId();
        if (id == R.id.help) {
    
           //do something
           return true;
        }
        if (id == R.id.new_game) {
    
           //do something
           return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

提交回复
热议问题