手势有问题。当我编译应用程序时,我遇到了错误:
System.NullReferenceException:未将对象引用设置为对象的实例。
在这一行:
view.GestureRecognizers.Add(panGesture);
我的整个代码:
private ISwipeCallBack mISwipeCallback;
private double translatedX = 0, translatedY = 0;
public SwipeListener(View view , ISwipeCallBack iSwipeCallBack)
{
mISwipeCallback = iSwipeCallBack;
var panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += OnPanUpdated;
view.GestureRecognizers.Add(panGesture);
}
void OnPanUpdated(object sender, PanUpdatedEventArgs e)
{
View Content = (View)sender;
switch (e.StatusType)
{
case GestureStatus.Running:
try
{
translatedX = e.TotalX;
translatedY = e.TotalY;
}
catch (Exception err)
{
System.Diagnostics.Debug.WriteLine("" + err.Message);
}
break;
case GestureStatus.Completed:
System.Diagnostics.Debug.WriteLine("translatedX : " + translatedX);
System.Diagnostics.Debug.WriteLine("translatedY : " + translatedY);
if (translatedX < 0 && Math.Abs(translatedX) > Math.Abs(translatedY))
{
mISwipeCallback.onLeftSwipe(Content);
}
else if (translatedX > 0 && translatedX > Math.Abs(translatedY))
{
mISwipeCallback.onRightSwipe(Content);
}
else if (translatedY < 0 && Math.Abs(translatedY) > Math.Abs(translatedX))
{
mISwipeCallback.onTopSwipe(Content);
}
else if (translatedY > 0 && translatedY > Math.Abs(translatedX))
{
mISwipeCallback.onBottomSwipe(Content);
}
else
{
mISwipeCallback.onNothingSwiped(Content);
}
break;
}
}
<StackLayout
>
<Label
x:Name="lbl_swipe"
Text="Welcome to Xamarin Forms! Drag it"
WidthRequest="300"
HeightRequest="200"
BackgroundColor="Yellow"
TextColor="Black"
FontSize="20"
VerticalOptions="Center"
HorizontalOptions="Center">
</Label>
<Label
x:Name="lbl_result"
WidthRequest="300"
HeightRequest="100"
BackgroundColor="Purple"
TextColor="White"
FontSize="20"
VerticalOptions="End"
HorizontalOptions="Center">
</Label>
</StackLayout>
的MainPage
public partial class Testowy : ContentPage, ISwipeCallBack
{
public Testowy()
{
SwipeListener swipeListener = new SwipeListener(lbl_swipe, this);
}
public void onBottomSwipe(View view)
{
if (view == lbl_swipe)
{
lbl_result.Text = "OnBottomSwipe";
}
}
public void onLeftSwipe(View view)
{
if (view == lbl_swipe)
{
lbl_result.Text = "onLeftSwipe";
}
}
public void onNothingSwiped(View view)
{
if (view == lbl_swipe)
{
lbl_result.Text = "onNothingSwiped";
}
}
public void onRightSwipe(View view)
{
if (view == lbl_swipe)
{
lbl_result.Text = "onRightSwipe";
}
}
public void onTopSwipe(View view)
{
if (view == lbl_swipe)
{
lbl_result.Text = "onTopSwipe";
}
}
}
答案 0 :(得分:2)
您错过了InitializeComponent
方法 - 该方法应初始化lbl_result
或lbl_swipe
等引用。
public Testowy()
{
InitializeComponent(); //<---- add this line here.
SwipeListener swipeListener = new SwipeListener(lbl_swipe, this);
}