Android拖放自动滚动

时间:2020-06-01 11:02:07

标签: c# xamarin drag-and-drop

我正在尝试找出当用户将项目拖动到屏幕边缘时如何自动滚动滚动视图。我真的没有从代码中得到期望的行为。有没有人有例子或可行的技术?

我有这个:

onDrag(View v, DragEvent e)
{
   case DragAction.Location:

    var currentPosition = (int)e.GetX();

    var point = GetTouchPositionFromDragEvent(v, e);

    System.Diagnostics.Debug.WriteLine($"DragAction.Location from {v.GetType()} => {currentPosition}");
    System.Diagnostics.Debug.WriteLine($"DragAction.GLOBAL   from {v.GetType()} => {point.X}");

    if (point.X > App.AppScreenWidth - 50)
    {
        _hostScrollView.ScrollToAsync(_hostScrollView.ScrollX + 30, 0, true);
    }

    if (point.X < 50)
    {
        _hostScrollView.ScrollToAsync(_hostScrollView.ScrollX - 30, 0, true);
    }    
}

public static Point GetTouchPositionFromDragEvent(View item, DragEvent e) 
{
    Rect rItem = new Rect();
    item.GetGlobalVisibleRect(rItem);
    return new Point(rItem.Left + (int)Math.Round(e.GetX()), rItem.Top + (int)Math.Round(e.GetY()));
}

这还具有仅在一个方向上奇怪地滚动的连锁效果,并且还要求用户继续移动项目以触发事件,这使我认为这甚至是尝试做的完全错误的地方此滚动。

任何朝着正确方向的指针或微动都将不胜感激。

1 个答案:

答案 0 :(得分:1)

在您的活动中

public class MainActivity : AppCompatActivity, View.IOnDragListener,View.IOnScrollChangeListener
private int mScrollDistance;
 ScrollView _hostScrollView= FindViewById<ScrollView>(Resource.Id.xxx);
_hostScrollView.SetOnScrollChangeListener(this);
public bool OnDrag(View v, DragEvent e)
        {
            var action = e.Action;

            var scrollView = v as ScrollView;

            switch (action)
            {
                case DragAction.Started:

                    break;
                case DragAction.Location:
                    
                        int y = Java.Lang.Math.Round(e.GetY());
                        int translatedY = y - mScrollDistance;
                        int threshold = 50;
                        // make a scrolling up due the y has passed the threshold
                        if (translatedY < threshold)
                        {
                            // make a scroll up by 30 px
                            scrollView.ScrollBy(0, -30);
                        }
                        // make a autoscrolling down due y has passed the 500 px border
                        if (translatedY + threshold > 500)
                        {
                            // make a scroll down by 30 px
                            scrollView.ScrollBy(0, 30);
                        }
                   
                    break;
                    
            }
            return true;
        }

        public void OnScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY)
        {
            var scrollView = v as ScrollView;
            mScrollDistance = scrollView.ScrollY;
        }

如果我误解了您的要求,您可以根据需要修改逻辑。