Robin
Robin

Reputation: 1

how to create an onclicklistener for a button?

The "Intent(this, MainActivity.class)" is underlined and the "startActivity(intent)" is in red. What did I do wrong here?

public class Main_Screen extends AppCompatActivity {

private Button listMoves = (Button) findViewById(R.id.listMoves);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_screen);
    listMoves.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(this, MainActivity.class);
            this.startActivity(intent);
            // Do something in response to button click
        }
    });
}

}

Upvotes: 0

Views: 329

Answers (1)

dominicoder
dominicoder

Reputation: 10165

The "Intent(this, MainActivity.class)" is underlined and the "startActivity(intent)" is in red. What did I do wrong here?

You didn't post the actual error the IDE is giving you.

But if I were to guess - you need to qualify this. Inside the anonymous click listener, this refers to the new listener object. But you're trying to launch an intent, which requires a Context, not a click listener.

So change:

Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);

To

Intent intent = new Intent(NameOfYourActivity.this, MainActivity.class);
startActivity(intent);

Upvotes: 1

Related Questions