如何从菜单切换到新的活动?
我有一个菜单,想在用户单击菜单项时打开一个新的活动:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_symbol:
System.out.println("ADD SYMBOL CLICKED!");
Intent myIntent = new Intent(this.getContext(), AddStocksActivity.class);
startActivityForResult(myIntent, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
我不确定如何正确创建我的意图
编译器错误:
The method getContext() is undefined for the type Main
I have a menu and would like to open a new Activity when the user clicks on the menu item:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.add_symbol:
System.out.println("ADD SYMBOL CLICKED!");
Intent myIntent = new Intent(this.getContext(), AddStocksActivity.class);
startActivityForResult(myIntent, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I'm not sure how to create my Intent properly
Compiler Error:
The method getContext() is undefined for the type Main
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将
this.getContext()
更改为this.getApplicationContext()
您正在尝试调用不存在的方法。
Change
this.getContext()
tothis.getApplicationContext()
You are trying to call a method that doesn't exist.
在你的活动类中做
在你的 onCreate() 中做
然后在你的选项中做
In your activity class do
In your onCreate() do
then in your Options thing, do
或者
or
由于
Main
扩展了Activity
(它扩展了Context
),您可以执行以下操作:Since
Main
extendsActivity
(which extendsContext
), you can do:这就是我所做的
}
希望有帮助
this is what I do
}
hope it helps