我正在开发一个应用程序,用户需要长时间按住按钮。
如何检测用户是:完成按下操作还是移动了触摸位置?
谢谢。
我正在开发一个应用程序,用户需要长时间按住按钮。
如何检测用户是:完成按下操作还是移动了触摸位置?
谢谢。
我认为你最好使用onLongClickListener()和onTouchListener()的组合来处理该按钮。由于onTouchListener()会触发每一个触摸事件,所以你需要在触摸监听器中捕获特定的事件。
试着使用以下代码:
class Blah extends Activity {
private Button mSpeak;
private boolean isSpeakButtonLongPressed = false;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.blahlayout);
Button mSpeak = (Button)findViewById(R.id.speakbutton);
mSpeak.setOnLongClickListener(speakHoldListener);
mSpeak.setOnTouchListener(speakTouchListener);
}
private View.OnLongClickListener speakHoldListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View pView) {
// Do something when your hold starts here.
isSpeakButtonLongPressed = true;
return true;
}
}
private View.OnTouchListener speakTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View pView, MotionEvent pEvent) {
pView.onTouchEvent(pEvent);
// We're only interested in when the button is released.
if (pEvent.getAction() == MotionEvent.ACTION_UP) {
// We're only interested in anything if our speak button is currently pressed.
if (isSpeakButtonLongPressed) {
// Do something when the button is released.
isSpeakButtonLongPressed = false;
}
}
return false;
}
}
}
pEvent.getAction() == MotionEvent.ACTION_UP
,而用户期望的是轻触并按住屏幕后自动开始处理,而不是轻触并按住然后松开。 - Bugs Happen如何检测用户完成按压的时刻
。如果您想要在检测到长按(即使按钮仍被按下)后触发某种行为,您可以使用longClickListener而不是使用此技术。 - John O'ConnorOnLongClickListener
返回false
,则仍会在长按结束时调用来自OnClickListener
的onClick
。这是检测长按结束的最简单方法。onTouch
并同时从onLongClick
返回false
(AS的默认设置且通常是您想要的),则可能会在不知情的情况下调用onClick
代码以结束长按。private boolean takingVideo = false;
captureButton.setOnClickListener(v -> {
// onClick gets called after normal click or long click
if(takingVideo) {
saveVideo();
} else {
takePhoto();
}
});
captureButton.setOnLongClickListener(v -> {
takeVideo();
return false;
});
private void takePhoto() {
// Save the photo
}
private void takeVideo() {
takingVideo = true;
// Start capturing video
}
private void saveVideo() {
takingVideo = false;
// Save the video
}
如您所见,当您允许Android将结束触摸事件传播给一个OnClickListener
时,逻辑就变得非常直观。
OnLongClickListener
中返回了 false
吗? - Ben Kane