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

人走茶凉 提交于 2019-12-29 03:58:05

问题


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();
    }
}

回答1:


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.




回答2:


Use default sounds from /system/media/audio/

MediaPlayer or SoundPool will help to implement playback.




回答3:


Consider using view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);.

It will do both: playing the default sound and vibrate if the user has it enabled in the global settings.



来源:https://stackoverflow.com/questions/11915983/playing-default-android-sound-of-button-clicking-ontouch-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!