You need to relocate the initialization step of MediaPlayer
, and put it inside of onCreate
method
import android.support.v7.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.widget.ImageView;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity
{
private MediaPlayer mediaPlayer;
private ImageView playImageView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this, R.raw.anthem);
playImageView = (ImageView) findViewById(R.id.playImageView);
playImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
mediaPlayer.start();
}
});
}
}
The suitable layout file looks:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="0.5dp">
<ImageView
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_media_play"
android:background="@android:color/black"
android:clickable="true"
android:focusable="true"
android:id="@+id/playImageView"
/>
</LinearLayout>
Check this link In order to have an ImageView with clickable effects.