我正在开发用户需要长时间按住按钮的应用程序。
如何检测用户的时刻:完成按下或移动他们的触摸位置?
谢谢
我认为您最好的选择是对该按钮使用 onLongClickListener() 和 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;
}
}
}
这些答案相当复杂。如果您onClick
从. 这是检测长按结束的最简单的地方。OnClickListener
false
OnLongClickListener
了解这一点尤其重要,因为如果您在返回时实现onTouch
路由(默认 AS 为您提供并且通常是您想要的),您的代码可能会在您长按结束时被调用,而您却没有意识到。false
onLongClick
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
.
我认为您可以为此使用OnTouchListener。
我认为onFocusChanged -Listener 可以用于此。