在我的应用程序
中,我需要做一些Action A
,同时为按钮
做正常的click
,并且需要在按住同一按钮超过 3
秒的同时执行其他一些Action B
。
我试过下面的代码
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;
}
});
但是它并没有像我期望的那样工作,任何人都请指导我完成这个操作。
最佳答案
所有回答和评论都是真实的。这是你的实现
Button button;
long down,up;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()){
case MotionEvent.ACTION_DOWN :
Toast.makeText(MainActivity.this, "Down", Toast.LENGTH_SHORT).show();
down=System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP :
Toast.makeText(MainActivity.this, "Up", Toast.LENGTH_SHORT).show();
up=System.currentTimeMillis();
if(up-down>3000)
Toast.makeText(MainActivity.this, "More than 3", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
}
关于Android 如何对同一个按钮同时使用 OnClick 和长按(3 秒),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37597203/