MCarter
MCarter

Reputation: 53

onPrepareOptionsMenu android app

I am trying to use the onPrepareOptionsMenu and when I press the menu, it does nothing!! Where am I going wrong?

Also, am I using the finish (); command right? When the user presses exit(menuX) I want them to exit the application completely, not the activity.

Thanks! :)

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

public boolean onPrepareOptionsMenu(MenuItem item){
    switch (item.getItemId()){
    case R.id.menuA:
        startActivity(new Intent("com.abc.example.A"));
        return true;
    case R.id.menuB:
        startActivity(new Intent("com.abc.example.B"));
        return true;
    case R.id.menuC:
        startActivity(new Intent("com.abc.example.C"));
        return true;
    case R.id.menuD:
        startActivity(new Intent("com.abc.example.D"));
    case R.id.menuX:
        finish();
    }
    return false;
}
}

Upvotes: 1

Views: 4662

Answers (2)

sebap123
sebap123

Reputation: 2685

First off all I would rather use onOptionsItemSelected then onPrepareOptionsMenu. Because as I understand you just want to press it. It is quite the same only first line is changed.

The second thing - app exit. Well, if this menu is in your main and first activity, then when you call finish() then this activity is destroyed (not exactly but the thing is that you don't see it anymore), so if app has no more activity everything is destroyed.

More advanced method for that is using instruction android.os.Process.killProcess(android.os.Process.myPid()); and what it is doing is simply sending kill signal for whole process. As far as your app won`t get bigger, I mean you will have only your activities in this process, than it is fine. Hope it will help.

Upvotes: 1

Wookie1120
Wookie1120

Reputation: 194

When I create an options menu, I usually use these two methods:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        menu.add(0, 1, 0, "option text");
            .....
    }

and

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    if(item.getItemId() == 1)
    ...
}

Also, with your switch statement, you are forgetting to put in break; for each option (which I notice mostly because I am notorious for doing the same).

Upvotes: 1

Related Questions