Simulate Long press by Touch events

本秂侑毒 提交于 2019-12-03 15:06:09

问题


How can we simulate long press by touch event? or how can we calculate the time that screen is touched, all in ACTION_DOWN state?


回答1:


I have implemented a Touch screen long click finally , thx all:

textView.setOnTouchListener(new View.OnTouchListener() {

    private static final int MIN_CLICK_DURATION = 1000;
    private long startClickTime;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
        case MotionEvent.ACTION_UP:
            longClickActive = false;
            break;
        case MotionEvent.ACTION_DOWN:
            if (longClickActive == false) {
                longClickActive = true;
                startClickTime = Calendar.getInstance().getTimeInMillis();
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (longClickActive == true) {
                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                if (clickDuration >= MIN_CLICK_DURATION) {
                    Toast.makeText(MainActivity.this, "LONG PRESSED!",Toast.LENGTH_SHORT).show();
                    longClickActive = false;
                }
            }
            break;
        }
        return true;
    }
});

in which private boolean longClickActive = false; is a class variable.




回答2:


For calculating touch count you can get getPointerCount() of your event like here

and for Long click maybe this helps

Edit: and hope this link help you determining getting touch duration




回答3:


You have to count time between ACTION_DOWN and ACTION_UP events. It's impossible to calculate this time only in ACTOIN_DOWN state, cause it's the START event of sequence of events representing TAP of LONG TAP event




回答4:


Try this. You don't need to find hack for this.

final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
 public void onLongPress(MotionEvent e) {
  Log.e("", "Longpress detected");
 }
});

public boolean onTouchEvent(MotionEvent event) {
 if (gestureDetector.onTouchEvent(event)) {
  return true;
 }
 switch (event.getAction()) {
  case MotionEvent.ACTION_UP:
   break;
  case MotionEvent.ACTION_DOWN:
   break;
  case MotionEvent.ACTION_MOVE:
   break;
 }
 return true;
}
};


来源:https://stackoverflow.com/questions/17896168/simulate-long-press-by-touch-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!