Scroll the button to top or bottom based on the finger movement

333 views Asked by At

I have a custom view, which takes touch events.As a result, I cannot use scrollview. Since the page size is small, I want to scroll the view, using a custom scrollbar button.

I'm able to scroll the view. But the problem is that I do not know, how to detect whether the user is moving the finger up or down. Right now I'm using onTouchListner to scroll down the view.

How to detect in which direction users finger is pointed? Here is my code:

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

     if (v == mScrollBtn) {
            int scrollBarHeight = mScrollBar.getHeight();;

            LayoutParams params = (LayoutParams) mScrollBtn.getLayoutParams();
            params.topMargin = SCROLL_FACTOR*mTopMargin;
            mTopMargin = mTopMargin + 1;
            if (params.topMargin <= mScrollBar.getHeight()-mBottomPadding) {
                mScrollBtn.setLayoutParams(params);
                // scrollDown(View.FOCUS_DOWN);
                mCustomView.scrollTo(0, mScrollBtn.getHeight() +SCROLL_FACTOR* mTopMargin);


}

Where SCROLL_FACTOR=2 & mTopMargin=2.

Thanks in Advance

1

There are 1 answers

0
Eldhose M Babu On BEST ANSWER

You can calculate the direction by simply moritoring the onMove values.

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        startX = event.getRawX();
        startY = event.getRawY();
        break;

    case MotionEvent.ACTION_MOVE:
        float newX = event.getRawX();
        float newY = event.getRawY();

        if (Math.abs(newX - startX) > Math.abs(newY - startY)) {
            // Means Horizontal Movement.
            if (newX - startX > 0) {
                // Moving Right
            } else {
                // Moving Left
            }
        } else {
            // Means Vertical Movement.
            if (newY - startY > 0) {
                // Moving Down
            } else {
                // Moving Up
            }
        }

        startX = newX;
        startY = newY;
        break;

    case MotionEvent.ACTION_UP:
        // Finger Up and the motion is complete
        startX = 0;
        startY = 0;
        break;
    }
    return super.onTouchEvent(event);
}