Make a scrollView autoscroll with drag and drop in Android

前端 未结 4 2027
借酒劲吻你
借酒劲吻你 2020-12-17 03:05

I searched all over, but could not find a solution.

I have a view (lets call it myView) inside a scrollview. myView is bigger than the screen. Since I\'m able to get

4条回答
  •  离开以前
    2020-12-17 03:56

    I came up with a different solution and I am happy with it.

    I want to be able to drag and drop views inside a ScrollView. The ScrollView then needs to scroll up and down automatically when the shadow reaches the edges of the scroll view.

    I ended up with a solution that detects wether the drop zone is completely visible inside the scrollview (with a 100px margin) and adjust the scroll view otherwise.

    @Override
    public boolean onDrag(View view, DragEvent event) {
    
        MainWidget dropZoneView = (MainWidget) view;
    
        int action = event.getAction();
        switch (action) {
            case DragEvent.ACTION_DRAG_STARTED:
            //(... other stuff happens here)
            case DragEvent.ACTION_DRAG_LOCATION:
    
                ScrollView mainScrollView = (ScrollView) findViewById(R.id.main_scroll);
    
                int topOfDropZone = dropZoneView.getTop();
                int bottomOfDropZone = dropZoneView.getBottom();
    
                int scrollY = mainScrollView.getScrollY();
                int scrollViewHeight = mainScrollView.getMeasuredHeight();
    
                Log.d(LOG_TAG,"location: Scroll Y: "+ scrollY + " Scroll Y+Height: "+(scrollY + scrollViewHeight));
                Log.d(LOG_TAG," top: "+ topOfDropZone +" bottom: "+bottomOfDropZone);
    
                if (bottomOfDropZone > (scrollY + scrollViewHeight - 100))
                    mainScrollView.smoothScrollBy(0, 30);
    
                if (topOfDropZone < (scrollY + 100))
                    mainScrollView.smoothScrollBy(0, -30);
    
                break;
            default:
                break;
        }
        return true;
    }
    

    Hope this helps!

提交回复
热议问题