Implementing an option menu in Android Studio

后端 未结 4 1810
名媛妹妹
名媛妹妹 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条回答
  •  萌比男神i
    2021-02-14 02:23

    In your java code, add this onCreateOptionsMenu to show optionMenu,

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.option_menu, menu); //your file name
            return super.onCreateOptionsMenu(menu);
        }
    

    Keep your under res\menu\option_menu folder,

    
    
    
    
    
    

    Now, if you want to set onOptionsItemSelected i.e onClick event for that ou can use,

    @Override
        public boolean onOptionsItemSelected(final MenuItem item) {
    
            switch (item.getItemId()) {
                case android.R.id.new_game:
                    //your code
                    // EX : call intent if you want to swich to other activity 
                    return true;
                case R.id.help:
                    //your code
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    

提交回复
热议问题