Search code examples
androidandroid-gridviewandroid-image

How to add Sound Effect on clicking an image in gridview


I am using a gridview that contain some images. I want to add sound effect on clicking each image in the gridview. I added images in res/raw folder and added the following code.

MediaPlayer mp;
gridView.setAdapter(new ImageAdapter(this));

gridView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView parent, View v,int position,long id) {
        if (position == 0) {
            mp = MediaPlayer.create(this, R.raw.ok);
            Toast.makeText(getBaseContext(),
                 "Shape Matched",
                 Toast.LENGTH_LONG).show();
            startActivity(new Intent("com.example.TestShapeActivity2"));
        } else {
            mp = MediaPlayer.create(this, R.raw.no);
            Toast.makeText(getBaseContext(),
                    "Please Try Again",
                    Toast.LENGTH_LONG).show();
            //startActivity(new Intent("com.example.TestShapeActivity2"));
        }
    }
});

But the create function gives the error

The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new AdapterView.OnItemClickListener(){}, int).

Please help me.Thank you.


Solution

  • Change the two calls to

    mp = MediaPlayer.create(this, R.raw.ok);
    

    to

    mp = MediaPlayer.create(TestShapeActivity.this, R.raw.ok);
    

    or whatever the name of the activity you are in is.

    create() takes a Context but when you refer to this within the OnItemClickListener it is referring to the listener, not the activity.

    Learn more about the this keyword here.