开发者

creating context menu in Android

开发者 https://www.devze.com 2023-03-16 09:57 出处:网络
I\'m trying to create an android context menu (the one that pops-up when you press the \'menu\' button\'). I\'ve read all the tutorials I could find and nothing helped. I\'m new to android developing.

I'm trying to create an android context menu (the one that pops-up when you press the 'menu' button'). I've read all the tutorials I could find and nothing helped. I'm new to android developing.

I've created the menu.xml file but I don't understand how to give functionality to ID's. This is how my code looks:

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch 开发者_如何学Python(item.getItemId()) {
    case R.id.new_game:
        newGame();
        return true;
    case R.id.help:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

The thing that I don't get: what to do with 'newGame();' and 'showHelp();'. I wish that when I click on a menu button a new activity starts. How do I do it?


First thing is you have code is for option menu not for context menu you can call new activity like below

  1. You can directly call a new activity without using option menu by

    Intent myIntent = new Intent(this, NewGame.class);
    startActivity(myIntent);
    
  2. if you want to give option to user on press menu button then try below code

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
    
            menu.add(0, 0, 0, "New Game");
            menu.add(0, 1, 1, "Help");
            return super.onCreateOptionsMenu(menu);
        }
    
    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
    
            if(item.getTitle().toString.equalsIgnoreCase("New Game")) {
    
                Intent intent = new Intent(this, NewGame.class);
                startActivity(intent);
                finish();
              }
                else if(item.getTitle().toString.equalsIgnoreCase("Help")) {
                     Toast.makeText(getBaseContext(), "Help", 2000).show();
                     }
            }
    


Intent intent = new Intent(this, NewGame.class);
startActivity(intent);

Have you read about how activity works?


This starts the activity NewGame

Intent myIntent = new Intent(this, NewGame.class);
startActivity(myIntent);
0

精彩评论

暂无评论...
验证码 换一张
取 消