java 使用 onClickListener (Intent) 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27704006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error using onClickListener (Intent)
提问by Skizo-oz??S
Well, I'm trying to create an intent on a "login.java" the code is :
好吧,我试图在“login.java”上创建一个意图,代码是:
Button btEntrar = (Button) findViewById(R.id.btnSingIn);
btEntrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i;
i = new Intent(this, MainActivity.class);
startActivity(i);
}
});
But it says that I can't go to the other activity saying this :
但它说我不能去其他活动说这个:
Error:(24, 21) error: no suitable constructor found for Intent(,Class) constructor Intent.Intent(String,Uri) is not applicable (argument mismatch; cannot be converted to String) constructor Intent.Intent(Context,Class) is not applicable (argument mismatch; cannot be converted to Context)
错误:(24, 21) 错误:没有找到合适的构造函数 Intent(,Class) 构造函数 Intent.Intent(String,Uri) 不适用(参数不匹配;无法转换为字符串)构造函数 Intent.Intent(Context,Class)不适用(参数不匹配;无法转换为上下文)
and...
和...
Error:Execution failed for task ':app:compileDebugJava'. Compilation failed; see the compiler error output for details.
错误:任务 ':app:compileDebugJava' 的执行失败。编译失败;有关详细信息,请参阅编译器错误输出。
回答by Sufiyan Ghori
Just a few lines to explain the reason why this
does not work in:
只需几行就可以解释为什么this
不起作用的原因:
i = new Intent(this, MainActivity.class)
The intent is created inside another class, here an anonymous inner class OnClickListener
. Thus this
does not refer the instance of your Activity (or Context) as intended but the instance of your anonymous inner class OnClickListener
.
意图是在另一个类中创建的,这里是一个匿名内部类OnClickListener
。因此this
,不会按预期引用您的 Activity(或上下文)的实例,而是引用您的匿名内部类的实例OnClickListener
。
So you should provide the correct context of your class.
所以你应该提供你班级的正确上下文。
i = new Intent(YourClassName.this, MainActivity.class)
回答by Abhishek Chaubey
use
if you want to send it from login.java
to mainactivity.class
use
如果你想从发送用它login.java
来mainactivity.class
使用
Intent intent=new Intent(login.this,Mainactivity.class);
startActivity(intent);
回答by Naveen Tamrakar
updated code in to your activity
将代码更新到您的活动中
Button btEntrar = (Button) findViewById(R.id.btnSingIn);
btEntrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i;
i = new Intent(login.this, MainActivity.class);
startActivity(i);
}
});
回答by Umair
try using
尝试使用
Intent i = new Intent(login.this, mainActivity.class);
hope this helps
希望这可以帮助
回答by previousdeveloper
Did you add manifest.xml or try this code ?Intent i = new Intent(login.this,mainActivity.class);
您是否添加了 manifest.xml 或尝试使用此代码?Intent i = new Intent(login.this,mainActivity.class);