向左或向右滑动以使用MVVMCross

时间:2016-03-16 22:08:04

标签: android mvvm xamarin mvvmcross

我的viewmodel中有以下项目列表。我在视图中一次显示一个项目。让我们说第一项是A.但当用户向右或向左滑动时,我希望View刷新并显示下一项,例如B.

我想知道使用mvvmcross如何向右或向左滑动可以迭代列表项?即使知道滑动的方向也足够了。

我正在查看以下网址以了解MvxGestureRecognizerBehavior但它已被破坏

https://github.com/MvvmCross/MvvmCross-Build/blob/master/MvvmCross/Cirrious/Cirrious.MvvmCross.Binding.Touch/Views/Gestures/MvxGestureRecognizerBehavior.cs

public RViewModel()
 {
    Items = new ObservableCollection<ListItem> {
        new ListItem { Title = "A" },
        new ListItem { Title = "B" },
        new ListItem { Title = "C" },
        new ListItem { Title = "D" },
        new ListItem { Title = "E" }
    };
 }

注意:请记住,我可以使用viewpager,但由于我在视图中加载类似的内容(只是TextView),我不想创建多个片段迭代每个项目。因此,我只想使用向左/向右滑动操作刷新TextView / View

1 个答案:

答案 0 :(得分:2)

使用处理滑动的方法创建接口IMotionViewModel。将其应用于ViewModel

在您的机器人活动中实施GestureDetector.IOnGestureListener界面。处理您需要的运动事件并访问那里的ViewModel并在那里传递运动或参数。

<强>视图模型

public interface IMotionViewModel
{
    void OnSwipe(bool swipeRight);
}

public class FirstViewModel : MvxViewModel, IMotionViewModel
{
    public ObservableCollection<ListItem> Items { get; set; }
    private string _currentString = "Hello MvvmCross";
    public string CurrentString
    {
        get { return _currentString; }
        set { SetProperty(ref _currentString, value); }
    }

    public FirstViewModel()
    {
        Items = new ObservableCollection<ListItem> {
                new ListItem { Title = "A" },
                new ListItem { Title = "B" },
                new ListItem { Title = "C" },
                new ListItem { Title = "D" },
                new ListItem { Title = "E" }
            };
    }

    public void OnSwipe(bool swipeRight)
    {
        //do list iteration here....
    }
}

Droid活动

[Activity(Label = "View for FirstViewModel")]
public class FirstView : MvxActivity, Android.Views.GestureDetector.IOnGestureListener
{
    private GestureDetector _gestureDetector;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.FirstView);
        _gestureDetector = new GestureDetector(this);
    }

    public override bool OnTouchEvent(MotionEvent e)
    {
        _gestureDetector.OnTouchEvent(e);
        return false;
    }

    public bool OnDown(MotionEvent e)
    {
        return false;
    }

    public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        var isSwipingRight = (e2.RawX - e1.RawX) > 0 ? true : false;

        var motionVm = base.ViewModel as IMotionViewModel;
        motionVm.OnSwipe(isSwipingRight);
        return true;
    }

    public void OnLongPress(MotionEvent e) { }

    public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        return false;
    }

    public void OnShowPress(MotionEvent e) { }

    public bool OnSingleTapUp(MotionEvent e)
    {
        return false;
    }
}