Playing default android sound of button, clicking onTouch() method

dmgmyza picture dmgmyza · Aug 11, 2012 · Viewed 19.1k times · Source

In my android app I have some buttons, that should work with onTouch() method, course I need to change button's text, when finger in ACTION_DOWN position. But this buttons should to play default android sound of button clicking (like in onClick() method). Where I can find such sound? I think, it must be in SDK, but how can I find it? And what methods are better for such operation? I'm using MediaPlayer.

Listing:

public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        addTextShadow(v);
        Log.v(LOG_TAG, "ACTION_DOWN");
        break;
    case MotionEvent.ACTION_MOVE:
        clearTextShadow(v);
        isMoved = true;
        Log.v(LOG_TAG, "ACTION_MOVE");
        break;
    case MotionEvent.ACTION_UP:
        Log.v(LOG_TAG, "ACTION_UP");
        if (!isMoved) {
            clearTextShadow(v);
            if (v.getId() == R.id.btn_new) {
                Log.v(LOG_TAG, "New pressed");

                            playSound(); //MY METHOD TO PLAY SOUND

            } else if (v.getId() == R.id.btn_saved) {
                Log.v(LOG_TAG, "Saved pressed");
            } else if (v.getId() == R.id.btn_random) {
                Log.v(LOG_TAG, "Random pressed");
            }
        }
        isMoved = false;
        break;
    }
    return true;
}

And my playSound() method:

    public void playSound(){
    if (mp != null) {
        mp.release();
        mp = null;
    }
    try {
        mp = MediaPlayer
    .create(MyActivity.this, R.raw.sound); //BUT HERE I NEED DEFAULT SOUND!
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Answer

Vishwa Patel picture Vishwa Patel · Aug 11, 2012

Use this code in your onTouch() method:

view.playSoundEffect(android.view.SoundEffectConstants.CLICK);

If you are simply looking for a preset Android sound then it's better to use this functionality that's provided to you for free by the framework. Doing anything else, unless necessary for customization, would simply result in you working against the framework instead of working with it.