-1

I need someone to correct my code. I am trying to make a clickable ImageView that can play a simple music file.

public class MainActivity extends AppCompatActivity {

    MediaPlayer media = MediaPlayer.create(this,R.raw.anthem);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView play = (ImageView)findViewById(R.id.play);
        play.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                media.start();
            }
        });

    }
}

I cannot find any errors, but the app refuses to work.

Elyas Hadizadeh
  • 3,289
  • 8
  • 40
  • 54
zebrahim
  • 3
  • 2

1 Answers1

0

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.

Elyas Hadizadeh
  • 3,289
  • 8
  • 40
  • 54