在滚动区域中拖动自定义视图

时间:2012-07-20 19:52:18

标签: android ontouchevent android-custom-view

所以我有一个自定义视图小部件我允许用户用手指拖动。他们在自定义滚动视图中拖动它基于包含RelativeLayout的FrameLayout(此处为代码:http://blog.gorges.us/2010/06/android-two-dimensional-scrollview/),以便他们可以将其放置在他们想要的位置,并且有足够的空间在屏幕上看不到该项目也是如此。

我想要发生的是,如果用户在可见滚动区域的边缘附近移动小部件是在适当的方向上滚动该区域,直到它们放开(ACTION_UP,在这种情况下不再需要更多事件)无论如何)或已离开边缘。现在的代码有两个问题:

1)我的手机(T-Mobile G2)继续触发ACTION_MOVE,即使我的手指仍然在我的Nexus 7平板电脑没有继续触发直到它移动的位置。我需要可靠地继续触发此事件,直到ACTION_UP。

2)区域滚动但只有当我将手指移向屏幕边缘时才会滚动。换句话说,我想要一个静止的手指继续滚动并移动物体,当它靠近边缘时,但这不会发生。

我错过了什么?这是处理小部件移动的onTouchEvent

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_MOVE
            && this.getParent() != null) {
        getParent().requestDisallowInterceptTouchEvent(true);
    }

    // mScrollParent gets set in a setter and points to the TwoDScrollView
    // mOffsetX/Y is based on where the user touches versus the position of the custom view
    // mWidth/mHeight gets set once in the GestureDetector based on the custom view's getWidth()/getHeight()
    // mTitleBarHeight gets set once in the GestureDetctor onDown event
    // lp is a ViewGroup.LayoutParams type
    if (!mGestureDetector.onTouchEvent(event)) {
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            int finalX = (int) (event.getRawX() - mOffsetX);
            int finalY = (int) (event.getRawY() - mOffsetY - (mTitleBarHeight > 0 ? mTitleBarHeight * 2
                    : 0));

            if (finalX < 0 || finalY < 0)
                return false;

            int scrollLeft = (int) Math.ceil(mScrollParent.getScrollX() * 1.05);
            int scrollTop = (int) Math.ceil(mScrollParent.getScrollY() * 1.05);
            int scrollRight = (int) Math.floor((scrollLeft + mScrollParent.getRight()) * 0.95);
            int scrollBottom = (int) Math.floor((scrollTop + mScrollParent.getBottom()) * 0.95);
            int scrollX = 0;
            int scrollY = 0;

            if (scrollLeft > finalX)
                scrollX = finalX - scrollLeft;

            if (scrollRight < (finalX + mWidth))
                scrollX = (finalX + mWidth)- scrollRight;

            if (scrollTop > finalY)
                scrollY = finalY - scrollTop;

            if (scrollBottom < (finalY + mHeight))
                scrollY = (finalY + mHeight) - scrollBottom;

            if (scrollX != 0 || scrollY != 0)
                mScrollParent.scrollBy(scrollX * 4, scrollY * 4);

            lp.setMargins(finalX + scrollX, finalY + scrollY, 0, 0);
            setLayoutParams(lp);

            return true;
        }
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
            return true;
        } else {
            return super.onTouchEvent(event);
        }
    } else {
        return true;
    }
}

0 个答案:

没有答案