[英]How to check if screen is touched for more than 2 seconds
哪個是最佳且更優化的策略,用於在不停止主UI線程的情況下檢查屏幕是否已被觸摸2秒或更長時間?
我已經檢查了一些示例代碼,但我不確定哪種方法是實現它的最佳方法,而且我還需要在不停止主UI線程的情況下執行此操作。
謝謝
您可以像這樣實現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()
方法。
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 ,long)
我用了一個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;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.