Android如何对同一个按钮同时使用OnClick和长按(3秒) [英] Android how to use both OnClick and Long press(3 sec) for same Button
问题描述
在我的application
中,我需要对button
做普通的click
时做一些Action A
,同时还需要在按住同一按钮超过3
秒的同时做一些其他Action B
.
我已经尝试过以下代码
In my application
I need to do some Action A
while doing normal click
for the button
and also need to do some other Action B
while holding the same button for more than 3
sec.
I have tried this below code
private boolean isMoved = false;
final Runnable runr = new Runnable() {
@Override
public void run() {
// Your code to run on long click
System.out.println("long pressed for 3 sec");
}
};
final Handler handel = new Handler();
contactButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
isMoved = false;
handel.postDelayed(runr,3000);
break;
case MotionEvent.ACTION_MOVE:
isMoved = true;
case MotionEvent.ACTION_UP:
if(!isMoved)
System.out.println("button single click");
default:
handel.removeCallbacks(runr);
break;
}
return true;
}
});
但是它没有按我期望的那样工作,请任何人指导我完成此操作.
But it is not working like what I expect,anyone please guide me to complete this operation.
推荐答案
Jamal. 您真的需要等待3秒钟吗?
Jamal. You really need to wait for 3 secs?
如果不需要等待3秒钟,请对单击操作使用setOnClickListener方法,对长按操作使用setOnLongClickListener方法.
If you don't need to wait for 3 secs, use the methods setOnClickListener for single click actions, and setOnLongClickListener for long click actions.
您可以在以下链接中查看它:
You can check it out in the following links:
-
如果您确实需要等待3秒钟,则必须检查ACTION_UP和ACTION_DOWN时间戳之间的时差.
In the case you really need to wait for 3 secs, you have to check the difference between the timestamp of the ACTION_UP and ACTION_DOWN.
public class YourClass {
private MotionEvent mLastEvent = MotionEvent.ACTION_UP;
final Runnable runr = new Runnable() {
@Override
public void run() {
if(mLastEvent == MotionEvent.ACTION_MOVE) {
// Your code to run on long click
}
}
};
final Handler handel = new Handler();
contactButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
mLastEvent = arg1.getAction();
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
handel.postDelayed(runr,3000);
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
default:
handel.removeCallbacks(runr);
break;
}
return true;
}
});
}
这篇关于Android如何对同一个按钮同时使用OnClick和长按(3秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!