在android中的scrollview中拖放

时间:2014-05-09 06:17:01

标签: android drag android-scrollview

我在LinearLayout中有一个ScrollView。我已向LinearLayout添加了一些视图,并且我希望在LinearLayout中的视图上实现向上和向下拖动。它就像您要订购的商品列表。

我使用DragShadowBuilderLongClickEvent上的DragListener部分执行此操作。

问题在于:

1)拖动超出父视图。我想将其限制在父LinearLayout内。

2)当我拖动视图时,ScrollView不会滚动。

请建议我如何实现这一点。

1 个答案:

答案 0 :(得分:0)

您可以使用此技巧使scrollview向下或向上滚动依赖于ShadowBuilder的位置:

@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;
}