使用onClickListener时出错(意图) [英] Error using onClickListener (Intent)

查看:112
本文介绍了使用onClickListener时出错(意图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在尝试在login.java上创建一个意图代码是:

Well, I'm trying to create an intent on a "login.java" the code is :

 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 :


错误:(24,21)错误:没有为Intent(,Class)找到合适的构造函数
构造函数Intent.Intent(String,Uri)is不适用
(参数不匹配;不能转换为String)
构造函数Intent.Intent(Context,Class)不适用
(参数不匹配;不能转换为Context)

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)

和...


错误:执行失败task':app:compileDebugJava'。
编译失败;有关详细信息,请参阅编译器错误输出。

Error:Execution failed for task ':app:compileDebugJava'. Compilation failed; see the compiler error output for details.


推荐答案

只需几行来解释原因不起作用:

Just a few lines to explain the reason why this does not work in:

i = new Intent(this, MainActivity.class)

意图是在另一个类中创建的,这里是一个匿名的内部类 OnClickListener 。因此不会按预期引用您的Activity(或Context)实例,而是匿名内部类的实例 OnClickListener

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.

所以你应该提供你班级的正确背景。

So you should provide the correct context of your class.

i = new Intent(YourClassName.this, MainActivity.class)

这篇关于使用onClickListener时出错(意图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆