2010-01-22 121 views
1

我是Android新手,我试图从MenuItem开始选择一个活动的用户。Android:从MenuItem开始活动

其实,我建立我的菜单(并且工作正常)使用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; 
    } 

和IM使用下面的代码(也没关系工作)处理菜单选择:

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

     default:  
     break; 
    } 
    return false; 
} 

我有一个名为AddWebsite第二和最后一项活动,我想启动它,但下面的代码不工作:

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

} 

你知道什么是我必须传递给Intent构造函数的额外的东西吗?

回答

7

的解决方案是太简单了,看来,在Android中,每一个活动类不会自动引用manifest.xml。

我只是将新的活动添加到清单,并且工作正常。

问候。 何塞

+0

既然这解决了你的问题,你可以接受你自己的答案。 – 2010-01-22 11:42:33

1

我对android自己还很陌生,但是你不需要传递一个上下文给Intent构造函数吗?

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

} 

你可能会做这从一个活动里面,所以我觉得你应该用“这个”

+0

嗨马特, 感谢您的答复。 我尝试了这个选项,但我得到一个错误,说应用程序已经完成了。 我Addwebsite活动的代码如下(也许有什么不妥...): 公共类AddWebsite扩展活动 { \t @覆盖 \t公共无效的onCreate(捆绑savedInstanceState) \t { \t超.onCreate(savedInstanceState); \t setContentView(R.layout.screenaddsite); \t} } 您是否在代码中看到其他奇怪的东西? 谢谢。 最好的问候。 何塞。 – Sosi 2010-01-22 10:24:02

1

你也可以做这样的事情

/* (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); 
} 

避免一些方法调用,但是你需要注意的菜单标识,菜单顺序和意图之间的映射,但这几乎总是已知的。