自定义视图和On Touch Listeners

时间:2017-11-27 08:14:24

标签: android ontouchlistener

我想要实现的是我有一个自定义视图。并且视图在屏幕上可以拖动。

但是,如果只点按视图,我将如何显示另一个视图?

关于如何实现我的需求,我的主要想法是查看视图是否被长时间点击然后它可以移动,如果不显示视图。

这是我的代码:

 collapsedLayout.setOnTouchListener(new View.OnTouchListener() {
        private int initialX;
        private int initialY;
        private float initialTouchX;
        private float initialTouchY;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                        initialX = params.x;
                        initialY = params.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();

                    return true;

                case MotionEvent.ACTION_UP:

                    return true;


                case MotionEvent.ACTION_MOVE:
                    params.x = initialX + (int) (event.getRawX() - initialTouchX);
                    params.y = initialY + (int) (event.getRawY() - initialTouchY);
                    mWindowManager.updateViewLayout(entireLayout, params);
                    return true;
            }
            return false;
        }
    });

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

private static final int THRESHOLD_X = 120;
private static final int THRESHOLD_Y = 120;
private static final int NONE = 0;
private static final int MOVE = 1;
private static int mode = NONE;  

collapsedLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch (motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    // Action Down
                    break;
                case MotionEvent.ACTION_MOVE:
                    if(view.getX() > THRESHOLD_X && view.getY()> THRESHOLD_Y){
                        // performDrag
                        mode = MOVE;
                        performDrag(view);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    // Action up
                    if(mode == MOVE){
                        // Do nothing and return
                        return true;
                    }
                    // Perform click to the view
                    view.performClick();
                    break;
                default:
                    // Handle default case.
                    break;
            }
            return false;
        }
    });