Sosi
Sosi

Reputation: 2578

Android: Start activity from a MenuItem

I'm new on Android, and I'm trying to start an Activity from a MenuItem choose of the user.

Actually, I'm building my menu (and is working OK) from my main activity class using a MenuInflater:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        super.onCreateOptionsMenu(menu);
        //the Menu Inflater class allows to create a menu from a XML File
        MenuInflater inflater = new MenuInflater(this);
        inflater.inflate(R.layout.menutest,menu);
        return true;
    }

And im handling the Menu selection using the following code (working fine too):

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) 
    {
        case R.id.MenuItemNewWebsite:
            ShowScreenAddSite();
        break;

        default:    
        break;
    }
    return false;
}  

I have a second and last activity called AddWebsite, and i would like to start it, but the following code doesnt work:

protected void ShowScreenAddSite()
{
    Intent i = new Intent(AddWebsite.class);
    startActivity(i);

}

Do you know what is the extra thing that I have to pass to the Intent constructor?

Upvotes: 1

Views: 13296

Answers (3)

Diego Torres Milano
Diego Torres Milano

Reputation: 69208

You can also do something like this

/* (non-Javadoc)
 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    final MenuInflater inflater = new MenuInflater(this);
    final Intent[] menuIntents = new Intent[] {
              new Intent(this, AddWebsite.class) };
    inflater.inflate(R.menu.mymenu, menu);
    final int ms = menu.size();
    for (int i=0; i < ms; i++) {
        menu.getItem(i).setIntent(menuIntents[i]);
    }
    return super.onCreateOptionsMenu(menu);
}

avoiding some method calls, however you need to pay attention to the mapping between menu ids, menu order and intents but this is almost always known.

Upvotes: 1

Sosi
Sosi

Reputation: 2578

the solution was too simple, appears that in android, every activity class is not automatically referenced in the manifest.xml.

I just only add the new activity to the manifest, and works fine.

Regards. Jose

Upvotes: 7

MattyW
MattyW

Reputation: 1529

I'm still quite new to android myself but don't you need to be passing a context to the Intent constructor?

protected void ShowScreenAddSite()
{
    Intent i = new Intent(this, AddWebsite.class);
    startActivity(i);

}

You're probably doing this from inside an activity so I think you should be using 'this'

Upvotes: 1

Related Questions