[英]why am i getting error when trying to open new activity in android studio
I'm getting this error when I write the intent inside the onCreate
method.当我在
onCreate
方法中写入意图时出现此错误。 But when I write the intent inside an outer method and call it, it works.但是当我在外部方法中编写意图并调用它时,它就起作用了。
Button click listener is an interface and you implemented it here as an anonymous class, so inside of that class this
refers to that anonymous class, not your activity class, but Intent
constructor needs activity class implementation, therefore as @ADITYA RANADE answered you need to change it to MainActivity.this
.按钮单击侦听器是一个接口,您在此处将其作为匿名类实现,因此在该类内部,
this
指的是该匿名类,而不是您的活动类,但Intent
构造函数需要活动类实现,因此正如@ADITYA RANADE 回答的那样,您需要将其更改为MainActivity.this
。
However if you replace anonymous class with lambda you can avoid this:但是,如果您用 lambda 替换匿名类,则可以避免这种情况:
Button button = new Button(context);
button.setOnClickListener(v -> {
Intent intent = new Intent(this, MainActivity.class);
});
在 Intent 中将其更改为MainActivity.this
Well that is because of the place or more precisely "context" (not the androidish Context) of where you are calling it.嗯,这是因为你调用它的地方或更准确地说是“上下文”(不是 androidish 上下文)。
When you call it from the anonymously created inner class which implements the listener for a view click, so in this case the this represents something else - anonymous class.当您从匿名创建的内部类调用它时,该内部类实现了视图单击的侦听器,因此在这种情况下, this代表其他内容 - 匿名类。
But on the other side when you make the method eg openScheduleActivity() inside the activity itself, the this keyword represents the activity itself and in fact represents the androidish Context or in this particular case even the activity.但是另一方面,当您在活动本身内部创建方法(例如 openScheduleActivity() )时, this关键字代表活动本身,实际上代表 androidish上下文,或者在这种特殊情况下甚至是活动。 So you can either stay with case that you have already had there and slightly edit it, or you can use lambda expression, or you can use the method inside the activity itself as you have already discovered.
因此,您可以保留已有的大小写并对其进行稍微编辑,或者您可以使用 lambda 表达式,或者您可以使用您已经发现的活动本身内部的方法。
edited case:编辑案例:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, schedule.class);
startActivity(intent);
}
});
lambda expression:拉姆达表达式:
button.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, schedule.class);
startActivity(intent);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.