onClick on dynamic button causes error "Cannot resolve constructor Intent"

Asked

Viewed 393 times

6

I’m trying to create a dynamic button, and in it put the click function.

Button btnJogarNovamente;
btnJogarNovamente = new Button(this);
btnJogarNovamente.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
btnJogarNovamente.setWidth(200);
btnJogarNovamente.setHeight(40);
btnJogarNovamente.setText("Jogar novamente");
btnJogarNovamente.setX(10); btnJogarNovamente.setY(40);
container.addView(btnJogarNovamente);

btnJogarNovamente.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent it;
        it = new Intent(this, Menu.class);
        startActivity(it);
    }
});

However, an error occurs on the line

it = new Intent(this, Menu.class);

Cannot resolve constructor 'Intent(anonymus android.view.View.OnClickListener, java.lang.Class minhapackage.Menu)'
  • Only one point here. When you insert one setLayoutParams for its component, Voce passes two parameters FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT being them width and height respectively. In your case, do not need to assign the height and width, only: btnJogarNovamente.setLayoutParams(new FrameLayout.LayoutParams(200, 40));

  • Android Studio is an IDE, I edited the title because you want to add the button is in the application you are developing

  • Well noted. Thank you

1 answer

8


The context when implementing a class changes:

btnJogarNovamente.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent it;
        it = new Intent(this, Menu.class);
        startActivity(it);
    }
});

When executing new Intent(this, Menu.class);, the this this referencing to your OnClickListener and not the Activity.

In this case Voce must reference its class:

new Intent(NomeDaClasse.this, Menu.class);
  • Thank you. It worked perfectly

  • 1

    @Vitorherrmann if it worked mark the answer as correct

Browser other questions tagged

You are not signed in. Login or sign up in order to post.