Android中Button被按下时的触发事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2615616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Triggering event when Button is pressed down in Android
提问by codeman
I have the following code for Android which works fine to play a sound once a button is clicked:
我有以下适用于 Android 的代码,单击按钮后可以正常播放声音:
Button SoundButton2 = (Button)findViewById(R.id.sound2);
SoundButton2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(2);
}
});
My problem is that I want the sound to play immediately upon pressing the button (touch down), not when it is released (touch up). Any ideas on how I can accomplish this?
我的问题是我希望在按下按钮(触地)时立即播放声音,而不是在释放时(触地)。关于我如何做到这一点的任何想法?
采纳答案by Peterdk
Maybe using a OnTouchListener
? I guess MotionEvent will have some methods for registering a touch on the object.
也许使用OnTouchListener
? 我猜 MotionEvent 会有一些方法来注册对象上的触摸。
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}))
回答by Macarse
You should do this: b is the button.
你应该这样做: b 是按钮。
b.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN ) {
mSoundManager.playSound(2);
return true;
}
return false;
}
});
回答by tomanesq
import android.view.MotionEvent;
import android.view.MotionEvent;