gpt4 book ai didi

java - 使用 onClickListener 时出错( Intent )

转载 作者:搜寻专家 更新时间:2023-10-30 19:49:29 24 4
gpt4 key购买 nike

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

 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);


}
});

但它说我不能去其他 Activity 说:

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)

和...

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

最佳答案

仅用几行代码就可以解释为什么this 不能工作的原因:

i = new Intent(this, MainActivity.class)

Intent 是在另一个类中创建的,这里是一个匿名内部类 OnClickListener。因此,this 并未按预期引用 Activity(或 Context)的实例,而是引用匿名内部类 OnClickListener 的实例。

所以你应该提供你的类的正确上下文。

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

关于java - 使用 onClickListener 时出错( Intent ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27704006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com