Toast提示框对于日常的开发非常有用,主要用于不需要用户确认的提示信息显示。
Xamarin.Forms自带的提示框需要用户点击确定,Android很好用Toast其实也可以实现滴。
首先,我们要创建一个接口类
using System;
using System.Threading.Tasks;
namespace MyTest
{
public interface IAppHandler
{
void ShowToastMessage(string strMessage, bool bLong = false);
}
}
然后在Android下面一个DependencyService继承类,暂时命名为AppHandlerImplementation.cs
using System;
using System.Threading.Tasks;
using Android.Content;
using MyTest.Droid.DependencyService;
[assembly: Xamarin.Forms.Dependency(typeof(AppHandlerImplementation))]
namespace MyTest.Droid.DependencyService
{
public class AppHandlerImplementation : IAppHandler
{
public AppHandlerImplementation()
{
}
public void ShowToastMessage(string strMessage, bool bLong = false)
{
Android.Widget.Toast.MakeText(Xamarin.Forms.Forms.Context, strMessage, bLong ? Android.Widget.ToastLength.Long : Android.Widget.ToastLength.Short).Show();
}
}
}
对于iOS,由于苹果的设计规范,是不推荐使用Toast这种提示框,原因是会造成用户困扰,但是也不影响过审,具体可以在iOS项目下添加Nugut组件Toast.iOS,项目地址是
https://github.com/andrius-k/Toast
同理也添加AppHandlerImplementation.cs,代码如下
using System;
using System.Threading.Tasks;
using GlobalToast;
using MyTest.iOS.DependencyService;
[assembly: Xamarin.Forms.Dependency(typeof(AppHandlerImplementation))]
namespace MyTest.iOS.DependencyService
{
public class AppHandlerImplementation : IAppHandler
{
public AppHandlerImplementation()
{
}
public void ShowToastMessage(string strMessage, bool bLong = false)
{
Toast.MakeToast(strMessage).SetPosition(ToastPosition.Center).SetDuration(bLong ? ToastDuration.Long : ToastDuration.Regular).Show();
}
}
}
为了方便调用,可以加两个静态扩展
public static void ShowToastMessage(this Xamarin.Forms.View view, string strMessage, bool bLong = false)
{
Xamarin.Forms.DependencyService.Get<IAppHandler>().ShowToastMessage(strMessage, bLong);
}
public static void ShowToastMessage(this Xamarin.Forms.ContentPage page, string strMessage, bool bLong = false)
{
Xamarin.Forms.DependencyService.Get<IAppHandler>().ShowToastMessage(strMessage, bLong);
}
这样子在ContentPage和ContentView里面执行this.ShowToastMessage("提示框内容");即可
网友评论