android menu code not working

安稳与你 提交于 2019-11-28 13:00:24

问题


I have been trying to figure out why my boolean is not changing when I press the button, when I changed it manually it worked, but it doesn't do any thing. I have tried to follow tutorials to the word but they don't work. Can anybody point out where I am going wrong?

public boolean onOptionsItemSelected(MenuItem menu) 
{
    MenuItem freeze = (MenuItem)findViewById(R.id.freeze);  
    // Handle item selection 
    switch (menu.getItemId()) { 
        case R.id.freeze: 
            if (freze == false){
                freze = true;
            } else {
                freze = false;
            }
            return true; 
        case R.id.toggleVolCount: 
            if (toggleVol == true){
                toggleVol = false;
            } else {
                toggleVol = true;
            }
            return true; 
        default: return super.onOptionsItemSelected(menu); 
    } 

Thanks for all your help, when I tried the code that was suggested and it didn't work I went back and changed the menu. Previously I had made a button with an onClick to create the menu, when created the icon with code the code that I had previously written worked fine. Hope this helps someone other than me so I don't feel like so much of an idiot.}


回答1:


In res folder create one folder menu like drawable

Create new xml file optionmenu.xml in that folder.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menuitem" 
        android:title="Prefs">
    </item>
         <item android:id="@+id/menuitem1" 
        android:title="Prefs1">
    </item>


</menu>

In onCreate method write this code....

setOptionMenu(R.menu.optionmenu);

and in overide method of Menu write this code.....

@Override
    public boolean onOptionsItemSelected(MenuItem menu) {
        switch (menu.getItemId()) {
        case R.id.menuitem:
            startActivity(new Intent(this, Prefs.class));
            break;

case R.id.menuitem1:
            startActivity(new Intent(this, Prefs1.class));
            break;
        default:
            break;
        }

        return true;
    }


来源:https://stackoverflow.com/questions/11077982/android-menu-code-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!