I have an app in which I want to display my own menu activity when the user presses the menu button. I am using the onCreateOptionsMenu method to launch my activity, returning false so that no menu is shown. This is my code:
Inte开发者_运维技巧nt intentMenu = new Intent(this, ActivityMenu.class);
startActivityForResult(intentMenu, 0);
return false;
This works, but only the first time the menu button is pressed. I understand this method is only called once. How can I get it to be called every time the user presses the menu button? Or should I be going for a different approach?
Do not use onCreateOptionsMenu(), wrong place. Here is how you do it by overriding onKeyDOwn() method in your Activity:
@Override
public boolean onKeyDown (int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_BACK) {
startActivityForResult(new Intent(this, ActivityMenu.class), 0);
return true;
}
return super.onKeyDown( keyCode, event );
}
create your menu class look like this:
public class GlobalMenu extends Activity
{
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.global_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.GlobalSettings:
// Write code to perform action
break;
case R.id.Globalrefresh:
// Write code to perform action
break;
case R.id.Globalexit:
// Write code to perform action
break;
default:
}
return true;
}
}
Now extend this class from your main Activity in which you wont to show menu , when you click on menu button.
And create .xml file look like :
精彩评论