问题描述
是否可以使用Xamarin Forms(不是Android或iOS专用)弹出窗口,就像Android与Toast一样,不需要用户交互,并且会在(短)时间后消失?
Is there any way using Xamarin Forms (not Android or iOS specific) to have a pop-up, like Android does with Toast, that needs no user interaction and goes away after a (short) period of time?
从搜索中发现的所有警报都是需要用户单击才能消失的警报.
From searching around all I'm seeing are alerts that need user clicks to go away.
推荐答案
有一个简单的解决方案.通过使用 DependencyService ,您可以轻松获取Toast -类似于Android和iOS中的方法.
There is a simple solution for this. By using the DependencyService you can easily get the Toast-Like approach in both Android and iOS.
在常用程序包中创建一个界面.
public interface IMessage
{
void LongAlert(string message);
void ShortAlert(string message);
}
Android部分
[assembly: Xamarin.Forms.Dependency(typeof(MessageAndroid))]
namespace Your.Namespace
{
public class MessageAndroid : IMessage
{
public void LongAlert(string message)
{
Toast.MakeText(Application.Context, message, ToastLength.Long).Show();
}
public void ShortAlert(string message)
{
Toast.MakeText(Application.Context, message, ToastLength.Short).Show();
}
}
}
iOS部分
在iO中,没有像Toast这样的本机解决方案,因此我们需要实现自己的方法.
In iOs there is no native solution like Toast, so we need to implement our own approach.
[assembly: Xamarin.Forms.Dependency(typeof(MessageIOS))]
namespace Bahwan.iOS
{
public class MessageIOS : IMessage
{
const double LONG_DELAY = 3.5;
const double SHORT_DELAY = 2.0;
NSTimer alertDelay;
UIAlertController alert;
public void LongAlert(string message)
{
ShowAlert(message, LONG_DELAY);
}
public void ShortAlert(string message)
{
ShowAlert(message, SHORT_DELAY);
}
void ShowAlert(string message, double seconds)
{
alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
{
dismissMessage();
});
alert = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
}
void dismissMessage()
{
if (alert != null)
{
alert.DismissViewController(true, null);
}
if (alertDelay != null)
{
alertDelay.Dispose();
}
}
}
}
请注意,在每个平台中,我们都必须向DependencyService注册我们的类.
Please note that in each platform, we have to register our classes with DependencyService.
现在您可以在我们项目的任何地方访问Toast服务.
Now you can access out Toast service in anywhere in our project.
DependencyService.Get<IMessage>().ShortAlert(string message);
DependencyService.Get<IMessage>().LongAlert(string message);
这篇关于相当于Xamarin形式的吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!