項目中信息提示框,貌似只有個DisplayAlert,信息提示太過於單一,且在有些場合Toast更加實用,以下是一個簡單的原生Toast的實現方法
項目地址:https://github.com/weiweu/TestProject/tree/dev/Toast
共享項目
定義一個接口IToast,包括Short和Long兩個方法:
public interface IToast { void LongAlert(string message); void ShortAlert(string message); }
安卓
在安卓平台實現接口的方法並注入,添加一個Toast_Android.cs文件:
[assembly: Dependency(typeof(Toast_Android))] namespace Sample.Droid { public class Toast_Android : IToast { public void LongAlert(string message) { Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long).Show(); } public void ShortAlert(string message) { Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short).Show(); } } }
Ios
在Ios平台實現接口的方法並注入,添加一個Toast_Ios.cs文件:
[assembly: Xamarin.Forms.Dependency(typeof(Toast_Ios))] namespace Sample.iOS { public class Toast_Ios : IToast { 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(); } } } }
使用方法
例如在2個按鈕的點擊事件中實現Toast
xaml:
<Button Text="Short Toast" Clicked="Short_Clicked"/> <Button Text="Long Toast" Clicked="Long_Clicked"/>
cs:
void Short_Clicked(object sender, EventArgs e)
{
DependencyService.Get<IToast>().ShortAlert("Short Toast"); } void Long_Clicked(object sender, EventArgs e) { DependencyService.Get<IToast>().LongAlert("Long Toast"); }