Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

Set visibility in Menu programmatically android

So, that′s what I wanna know. How can I set the visibility of the menu programatically in Android?? This is how I have my menu:

public boolean onCreateOptionsMenu(Menu menu){
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

public boolean onOptionsItemSelected (MenuItem item){
    switch (item.getItemId()){
        case R.id.menuregistrar:
            break;
        case R.id.menusalir:
            break;
    }
    return true;
}

But this code is not on the onCreate, so I don′t know how to set one item visible or invisible programmatically (in my case, I want the "menuregistrar" to be invisible once I have registered my application and forever.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Put this method in your Activity

public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem register = menu.findItem(R.id.menuregistrar);      
    if(userRegistered) 
    {           
        register.setVisible(false);
    }
    else
    {
        register.setVisible(true);
    }
    return true;
}

in shorter version you could write:

MenuItem register = menu.findItem(R.id.menuregistrar);      
register.setVisible(!userRegistered);  //userRegistered is boolean, pointing if the user has registered or not.
return true;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...