播放的声音,而按钮是pressed -Android按钮、声音、Android、pressed

2023-09-06 03:27:50 作者:若如初

我有这个code

package com.tct.soundTouch;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class main extends Activity implements OnTouchListener {

    private MediaPlayer mp;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button zero = (Button) this.findViewById(R.id.button);
        zero.setOnTouchListener(this);

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

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:
            mp.setLooping(true);
            mp.start();

        case MotionEvent.ACTION_UP:
            mp.pause();
        }

        return true;
    }

}

和它的工作原理,但并不如我所料。在播放声音,但仅适用于我preSS按钮各一次。我的想法是。虽然我preSS播放声音,按钮,当我停止动作(指出按钮),音乐暂停。

and it works but not as i expected. The sound plays but only for each time that i press the button. My idea is. While i press the button the sound plays, when i stop the action (finger out of the button) music pause.

任何想法吗?

感谢

推荐答案

这应该工作(有一些错误的开关情况下,我认为):

This should work (there was something wrong with your switch-cases I think):

@Override
public boolean onTouch(View v, MotionEvent event) 
{   

    switch (event.getAction()) 
    {

    case MotionEvent.ACTION_DOWN:
    {
        mediaPlayer.setLooping(true);
        mediaPlayer.start();
    }

    break;
    case MotionEvent.ACTION_UP:
    {
        mediaPlayer.pause();
    }
    break;
}

return true;
}