检测触摸事件时,从另一种观点拖过一个观点观点、事件

由网友(其实我不笨只不过懒得聪明)分享简介:我如何检测触摸事件,如果用户触摸视图A和拖动到底部在视图B.我要检测的触摸事件的视图B。How do I detect the touch event if the user touches on view A and drags to bottom over the view B. I want to detect...

我如何检测触摸事件,如果用户触摸视图A和拖动到底部在视图B.我要检测的触摸事件的视图B。

How do I detect the touch event if the user touches on view A and drags to bottom over the view B. I want to detect the touch event in View B.

我增添一抹监听器视图B,但不接收事件,如果用户最初触及并拖过对B。

I added touch listener in view B but doesn't receive events if the user initially touched A and dragged over the B.

推荐答案

您可以用code娄才达到你的要求:

You can use the code bellow to achive your request:

的方法来测试视图边界(在code beloow使用)

Method to test view bounds (used in code beloow)

    Rect outRect = new Rect();
    int[] location = new int[2];

    private boolean inViewInBounds(View view, int x, int y){
        view.getDrawingRect(outRect);
        view.getLocationOnScreen(location);
        outRect.offset(location[0], location[1]);
        return outRect.contains(x, y);
    }

测试有两个的TextView

Testing with two TextView

    final TextView viewA = (TextView)  findViewById(R.id.textView);
    final TextView viewB = (TextView)  findViewById(R.id.textView2);

设置viewA

OnClickListener 必须保持 OnTouchListener 活动状态,直到 ACTION_UP

The empty OnClickListener is required to keep OnTouchListener active until ACTION_UP

    viewA.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {}
    });

    viewA.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int x = (int)event.getRawX();
            int y = (int)event.getRawY();
            if(event.getAction() == MotionEvent.ACTION_UP){
                if(inViewBounds(viewB, x, y))
                    viewB.dispatchTouchEvent(event);
                else if(inViewBounds(viewA, x, y)){
                    Log.d(TAG, "onTouch ViewA");
                    //Here goes code to execute on onTouch ViewA
                }
            }
            return false;
        }
    });

设置viewB

这是唯一必需的,如果你也想在viewB preSS并拖动到viewA

This is only required if you also want to press on viewB and drag to viewA

    viewB.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {}
    });

    viewB.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int x = (int)event.getRawX();
            int y = (int)event.getRawY();
            if(event.getAction() == MotionEvent.ACTION_UP){
                if(inViewBounds(viewA, x, y))
                    viewA.dispatchTouchEvent(event);
                else if(inViewBounds(viewB, x, y)){
                    Log.d(TAG, "onTouch ViewB");
                    //Here goes code to execute on onTouch ViewB
                }
            }
            return false;
        }
    });

问候。

阅读全文

相关推荐

最新文章