Android long press with scroll

2020-03-26 16:55发布

问题:

I want to "connect" long press with scroll, so the user doesn't have to release the screen and start to scroll.

I have gesture detector implemented...

final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
    public void onLongPress(MotionEvent e) {
        // action 1
    }

    public boolean onScroll(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
        // action 2
    }       
}

public boolean onTouchEvent(MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}    

But now between action 1 and action 2, user have to release the screen... How can I connect this actions without releasing the screen??

回答1:

I don't think a GestureDetector will do what you want, more likely you'll have to do it yourself. I don't know your current setup, below is a class with a OnToucListener tied to a ScrollView which will take in consideration both events:

public class ScrollTouchTest extends Activity {

    private final int LONG_PRESS_TIMEOUT = ViewConfiguration
            .getLongPressTimeout();
    private Handler mHandler = new Handler();
    private boolean mIsLongPress = false;
    private Runnable longPress = new Runnable() {

        @Override
        public void run() {         
            if (mIsLongPress) {             
                actionOne();
                mIsLongPress = false;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.views_scrolltouchtest);
        findViewById(R.id.scrollView1).setOnTouchListener(
                new OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        final int action = event.getAction();
                        switch (action) {
                        case MotionEvent.ACTION_DOWN:
                            mIsLongPress = true;                            
                            mHandler.postDelayed(longPress, LONG_PRESS_TIMEOUT);
                            break;
                        case MotionEvent.ACTION_MOVE:
                            actionTwo(event.getX(), event.getY());
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            mIsLongPress = false;
                            mHandler.removeCallbacks(longPress);
                            break;
                        }
                        return false;
                    }
                });
    }

    private void actionOne() {
        Log.e("XXX", "Long press!!!");
    }

    private void actionTwo(float f, float g) {
        Log.e("XXX", "Scrolling for X : " + f + " Y : " + g);
    }

}