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

}



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dominicoder