-5

I'm trying to show a Toast when the user clicks on the Play button. But makeText is red in my code, and it won't run. Where am I turning wrong?

Here is the Java code:

    // Find the View that shows the play_a button
    ImageView play_a = findViewById(R.id.play_a);

    // Set a click listener on that View
    play_a.setOnClickListener(new View.OnClickListener() {
        // The code in this method will be executed when play_a is clicked on.
        Toast.makeText(this, "Sorry, Play doesn't work", Toast.LENGTH_LONG).show();
    });

Is the problem that I need to override setOnClickListener?

davidtspf
  • 43
  • 1
  • 1
  • 6
  • 1
    Possible duplicate of [Android, using Toast inside onClickListener](https://stackoverflow.com/questions/40437997/android-using-toast-inside-onclicklistener) – Lucas Cabrales Apr 20 '18 at 21:52

2 Answers2

2

this keyword in makeText refers to anonymous-inner-class of type OnClickListener. You need to change it to pass the Context.

For example: play_a.getContext() or the way you like to refer.

waqaslam
  • 67,549
  • 16
  • 165
  • 178
1

You have to override the onClick function.

play_a.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"Sorry, Play doesn't work", Toast.LENGTH_LONG).show();
        }
    });
Anik Raj
  • 76
  • 6