Toast提示框?qū)τ谌粘5拈_(kāi)發(fā)非常有用,主要用于不需要用戶確認(rèn)的提示信息顯示。
Xamarin.Forms自帶的提示框需要用戶點(diǎn)擊確定,Android很好用Toast其實(shí)也可以實(shí)現(xiàn)滴。
首先,我們要?jiǎng)?chuàng)建一個(gè)接口類(lèi)
using?System;
using?System.Threading.Tasks;
namespace?MyTest
{
????public?interface?IAppHandler
????{?
????????void?ShowToastMessage(string?strMessage,?bool?bLong?=?false);
????}
}
然后在Android下面一個(gè)DependencyService繼承類(lèi),暫時(shí)命名為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();
? ? ? ? }
? ? }
}
對(duì)于iOS,由于蘋(píng)果的設(shè)計(jì)規(guī)范,是不推薦使用Toast這種提示框,原因是會(huì)造成用戶困擾,但是也不影響過(guò)審,具體可以在iOS項(xiàng)目下添加Nugut組件Toast.iOS,項(xiàng)目地址是
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();
????????}
????}
}
為了方便調(diào)用,可以加兩個(gè)靜態(tài)擴(kuò)展
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里面執(zhí)行this.ShowToastMessage("提示框內(nèi)容");即可