2016-03-01 78 views
2

嘿,我正在工作Xamarin Forms,我正在处理android双击的问题。禁用Android双击Xamarin Forms标签

我的问题是我使用标签作为按钮 - 当我点击这个快速,应用程序将崩溃。我想通过点击后禁用点击来阻止这种情况。

我的标签在XAML定义是这样的:

<Label x:Name="LabelName" Text="LabelText"/> 

我的后台代码是这样的:

LabelName.GestureRecognizers.Add((new TapGestureRecognizer 
{ 
    Command = new Command(async o => 
    { 
    await Navigation.PopToRootAsync(); 
    }) 
})); 

回答

2

好了,你可以有一个外部的布尔避免(也,不知道,但暂时禁用标签可以工作):

//On the form, so you can use a reference to This, else this is a value variable and will be copied and false always 
bool disable = false; 

然后:

LabelName.GestureRecognizers.Add((new TapGestureRecognizer 
{ 
    Command = new Command(async o => 
    { 
    if(this.disable) 
     return; 

    this.disable = true; 

    await Navigation.PopToRootAsync(); 

    this.disable = false; 
}) 
})); 
0

您需要制作一个禁用视图的操作。您可以添加可配置的超时以禁用它。 你可以实现它点击或视图,并添加任何其他方法,你喜欢控制新闻。 您的代码应该是这样的:

public abstract class ThrottlingListener : Java.Lang.Object 
    { 
     readonly TimeSpan timeout; 

     protected ThrottlingListener(TimeSpan timeout = default(TimeSpan)) 
     { 
      this.timeout = timeout == TimeSpan.Zero ? TimeSpan.FromSeconds(1) : timeout; 
     } 

     protected bool IsThrottling() 
     { 
      var now = DateTime.UtcNow; 
      if (now - LastClick < timeout) 
      { 
       return true; 
      } 
      LastClick = now; 
      return false; 
     } 

     protected DateTime LastClick{ get; private set;} 

     protected void DisableView(View view) 
     { 
      view.Enabled = false; 
      view.PostDelayed (() => 
      { 
       view.Enabled = true; 
      }, (long)timeout.TotalMilliseconds); 
     } 
    } 

    public class ThrottlingOnClickListener : ThrottlingListener, View.IOnClickListener 
    { 
     readonly Action onClick; 

     public ThrottlingOnClickListener(Action onClick, TimeSpan timeout = default(TimeSpan)) : base(timeout) 
     { 
      this.onClick = onClick; 
     }  

     public void OnClick(View view) 
     { 
      if (IsThrottling()) 
       return; 

      DisableView (view); 
      onClick(); 
     } 

    } 
0

在Android上,UI注册多个水龙头和队列起来执行一前一后。因此,双击按钮可以执行两次命令并导致意外行为。最简单的方法是让你的命令观察一个布尔属性并打开/关闭该属性。事情是这样的,

SomeCommand = new Command (OnCommand,(x)=> CanNavigate); 

async void OnCommand (object obj) 
{ 
        CanNavigate = false; 

        await CurrentPage.DisplayAlert ("Hello", "From intelliAbb", "OK"); 

        CanNavigate = true; 

} 

您可以检出在https://intelliabb.com/2017/02/18/handling-multiple-taps-in-xamarin-forms-on-android/

0

完整的示例下面是我在C#中做:

private static object _tappedLockObject = new object(); 
private static bool _tapped = false; 

private void tapHandler() 
{ 
    // one-at-a-time access to this block prevents duplicate concurrent requests: 
    lock(_tappedLockObject) 
    { 
     if(_tapped) return; 
     _tapped = true; 
    } 
    handleTap(); 
} 

private void reenableTap() 
{ 
    _tapped = false; 
} 

有了这个解决方案,你仍然会得到多个水龙头噪音。但这是一个不同的问题,对吧?