检测在正常的 Android Activity 上滑动 [英] Detection of swiping on a normal Android Activity

查看:26
本文介绍了检测在正常的 Android Activity 上滑动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在正常的 Android 活动中检测到用户向左/向右滑动?还是我必须使用 SwipeView?

Is it possible, to detect a swiping to the left/right of the user in a normal Android activity? Or do I have to use a SwipeView?

推荐答案

如果您正在寻找 Xamarin/C# 示例

在您的 Activity(或视图)上实现 GestureDetector.IOnGestureListener 并在 OnFling 方法中计算触摸的方向:

Implement GestureDetector.IOnGestureListener on your Activity (or view) and calculate the direction of the touch in the OnFling method:

[Activity(Label = "Swiper", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity, GestureDetector.IOnGestureListener
{
    GestureDetector gestureDetector;
    const int SWIPE_DISTANCE_THRESHOLD = 100;
    const int SWIPE_VELOCITY_THRESHOLD = 100;

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

    public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        float distanceX = e2.GetX() - e1.GetX();
        float distanceY = e2.GetY() - e1.GetY();
        if (Math.Abs(distanceX) > Math.Abs(distanceY) && Math.Abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.Abs(velocityX) > SWIPE_VELOCITY_THRESHOLD)
        {
            if (distanceX > 0)
                OnSwipeRight();
            else
                OnSwipeLeft();
            return true;
        }
        return false;
    }

    void OnSwipeLeft()
    {
        Button button = FindViewById<Button>(Resource.Id.myButton);
        button.Text = "Swiped Left";
    }

    void OnSwipeRight()
    {
        Button button = FindViewById<Button>(Resource.Id.myButton);
        button.Text = "Swiped Right";
    }

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

    public bool OnTouch(View v, MotionEvent e)
    {
        return gestureDetector.OnTouchEvent(e);
    }

    public override bool OnTouchEvent(MotionEvent e)
    {
        gestureDetector.OnTouchEvent(e);
        return false;
    }
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.Main);

        gestureDetector = new GestureDetector(this);
    }
}

这篇关于检测在正常的 Android Activity 上滑动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆