tango3d
tango3d

Reputation: 3

Image Button set background onClick

I have an image button when pressed it changes your background, here is the code of change in the xml button:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pushed"
        android:state_pressed="true"/>
    <item android:drawable="@drawable/normal"/>
</selector>

This button plays a sound when you press it, the problem is that if I keep clicking (long click) on the button that changes its background correctly and keeps showing the background for this state but does not play the sound until release. Here code:

        @Override
        public void onClick(View view) {
            mp = MediaPlayer.create(MyActivity.this,R.raw.sound);
            mp.start();

I want to play the sound when I touch it and not when I released it thanks in advance!

Upvotes: 0

Views: 207

Answers (1)

Akash Jindal
Akash Jindal

Reputation: 505

Use this code to accomplish your task

 imageButton.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){

                mp = MediaPlayer.create(MyActivity.this,R.raw.sound);
                mp.start();

                return true;
            }

           else  if(event.getAction() == MotionEvent.ACTION_UP){
                  mp.stop();
                  mp.release();
            return true;
        }

            return false;
        }
    });

Upvotes: 2

Related Questions