假设有一个ImageView(iv),并且在创建新的GestureDetector(gs)iv.SetOnTouchListener(this)
时设置了gs = new GestureDetector(this.Context, listener)
,我如何每0.01秒固定一次手指的位置(x,y)(如
一个例子)?
我应该使用哪个功能? OnFling
? OnLongPress
?
我不仅在谈论代码,而且我还想了解如何实现每0.01秒获取一次手指位置的愿望。有什么想法吗?
答案 0 :(得分:1)
您可以实现View.IOnTouchListener
接口并将其作为侦听器应用于您的View(在这种情况下为ImageView
):
注意:在此示例中,将Java.Lang.Object用作基类,但是您可以使用任何基于Java.Lang.Object
的类(Activity等)
public class MyTouch : Java.Lang.Object, View.IOnTouchListener
{
TimeSpan Milli10 = TimeSpan.FromMilliseconds(10);
DateTime oldTime;
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
oldTime = DateTime.Now;
break;
case MotionEventActions.Move:
if (DateTime.Now.Subtract(oldTime) > Milli10)
{
Console.WriteLine($"Touch {e.RawX} : {e.RawY} : tD: {DateTime.Now.Subtract(oldTime)}");
oldTime = DateTime.Now;
}
break;
default:
break;
}
return true;
}
}
然后仅在需要时实例化侦听器,并将其用作OnTouchListener
:
imageView = FindViewById<ImageView>(Resource.Id.background);
touch = new MyTouch();
imageView.SetOnTouchListener(touch);
需要添加LongPress,DoubleTap等...,子类GestureDetector.SimpleOnGestureListener
并将其作为内部类添加到View.IOnTouchListener实现中(这只是一种方法...)
public class MyTouchPlusGestures : Java.Lang.Object, View.IOnTouchListener
{
readonly MyGestures myGestures = new MyGestures();
readonly TimeSpan Milli10 = TimeSpan.FromMilliseconds(10);
readonly GestureDetector gestureDetector;
DateTime oldTime = DateTime.Now;
internal class MyGestures : GestureDetector.SimpleOnGestureListener
{
public override void OnLongPress(MotionEvent e)
{
// do something with press
base.OnLongPress(e);
}
public override bool OnDoubleTap(MotionEvent e)
{
// do something with tap
return base.OnDoubleTap(e);
}
}
public MyTouchPlusGestures(View view)
{
gestureDetector = new GestureDetector(view.Context, myGestures);
view.SetOnTouchListener(this);
}
public bool OnTouch(View v, MotionEvent e)
{
if (!gestureDetector.OnTouchEvent(e))
{
// If the event is not handled in one of your gestures,
// fall through to the MotionEventActions switch.
switch (e.Action)
{
case MotionEventActions.Down:
oldTime = DateTime.Now;
break;
case MotionEventActions.Move:
if (DateTime.Now.Subtract(oldTime) > Milli10)
{
Console.WriteLine($"Touch {e.RawX} : {e.RawY} : tD: {DateTime.Now.Subtract(oldTime)}");
oldTime = DateTime.Now;
}
break;
default:
break;
}
}
return true;
}
}
现在,只需将视图传递到您的MyTouchPlusGestures
实例,即可为您分配手势和触摸监听器...
imageView = FindViewById<ImageView>(Resource.Id.background);
touch = new MyTouchPlusGestures(imageView);