在不停止主UI线程的情况下检查屏幕是否已被触摸2秒或更长时间哪个是最佳且更优化的策略?
我已经检查了一些示例代码,但我不确定哪种方法是实现它的最佳方法,而且我还需要在不停止主UI线程的情况下执行此操作。
由于
答案 0 :(得分:2)
您可以像这样实施OnTouchListener
:
public abstract class TouchTimer implements View.OnTouchListener {
private long touchStart = 0l;
private long touchEnd = 0l;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
this.touchStart = System.currentTimeMillis();
return true;
case MotionEvent.ACTION_UP:
this.touchEnd = System.currentTimeMillis();
long touchTime = this.touchEnd - this.touchStart;
onTouchEnded(touchTime);
return true;
case MotionEvent.ACTION_MOVE:
return true;
default:
return false;
}
}
protected abstract void onTouchEnded(long touchTimeInMillis);
}
您可以这样使用它:
view.setOnTouchListener(new TouchTimer() {
@Override
protected void onTouchEnded(long touchTimeInMillis) {
// touchTimeInMillis contains the time the touch lasted in milliseconds
}
});
触摸结束后调用方法onTouchEnded()
。
答案 1 :(得分:0)
Android代码的所有手势检测部分内部使用Handler类和postDelayed方法的组合。您可以使用它来发布要在任意时间(例如2秒)之后运行的代码片段。
等待2秒钟才能运行代码
Runnable runnable;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
runnable = new Runnable() {
@Override
public void run() {
//do something
}
};
getHandler().postDelayed(runnable, 2000);
} else if (ev.getAction() == MotionEvent.ACTION_UP
|| ev.getAction() == MotionEvent.ACTION_CANCEL) {
getHandler().removeCallbacks(runnable);
}
return super.dispatchTouchEvent(ev);
}
见:http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable,长)
答案 2 :(得分:0)
我在OnTouchListener
上使用RelativeLayout
。我希望这会对你有所帮助。
RelativeLayout ll = (RelativeLayout) findViewById(R.id.ll);
ll.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
if (clickDuration >= MIN_CLICK_DURATION) {
Toast.makeText(MainActivity.this, "TOUCHED FOR" + clickDuration + "MS", Toast.LENGTH_SHORT).show();
}
longClickActive = false;
break;
case MotionEvent.ACTION_DOWN:
if (longClickActive == false) {
longClickActive = true;
Toast.makeText(MainActivity.this, "touch!", Toast.LENGTH_SHORT).show();
startClickTime = Calendar.getInstance().getTimeInMillis();
}
break;
case MotionEvent.ACTION_MOVE:
if (longClickActive == true) {
longClickActive = false;
}
break;
}
return true;
}
});