简体   繁体   中英

onTouchListener not accepting layout

Code

private RelativeLayout mToolbar;
mToolbar = (RelativeLayout) myview.findViewById(R.id.toolbar);

mToolbar.setOnTouchListener(new View.OnTouchListener() {
        WindowManager.LayoutParams updatedParameters = finalParameters;
        double x;
        double y;
        double pressedX;
        double pressedY;

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

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    x = updatedParameters.x;
                    y = updatedParameters.y;

                    pressedX = event.getRawX();
                    pressedY = event.getRawY();

                    break;

                case MotionEvent.ACTION_MOVE:
                    updatedParameters.x = (int) (x + (event.getRawX() - pressedX));
                    updatedParameters.y = (int) (y + (event.getRawY() - pressedY));

                    wm.updateViewLayout(myview, updatedParameters);

                default:
                    break;
            }

            return false;
        }
    });

I have a service and this above code can move around that service in the screen... It worked before when i had to touch a button and move it around. I switched it to layout now and it does.t work anymore Why doesn't this work? The same code i used it with a button instead and it worked fine. Does onTouch always have to be button or can it be layouts or textviews as well?

You should return true from onTouch method

If you return false when you get MotionEvent.ACTION_DOWN , Android assumes that you're not interested in handling touch events and simply doesn't pass any other motion events to you (including MotionEvent.ACTION_MOVE that you're expecting)

You need to update the return part of onTouch Method

  public boolean onTouch(View v, MotionEvent event) {
    // if return is true means touch enabled
    // If return is false means touch is disabled
    return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM