onclick on dynamic button causes error "Can not resolve constructor Intent"

6

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

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)'
    
asked by anonymous 17.07.2015 / 15:38

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 running new Intent(this, Menu.class); , this is referencing your OnClickListener and not Activity .

In this case you should reference your class:

new Intent(NomeDaClasse.this, Menu.class);
    
17.07.2015 / 16:12