开发者

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 la开发者_StackOverflow中文版st 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?


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


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'


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜