Toast equivalent on Xamarin Forms -
is there way using xamarin forms (not android or ios specific) have popup, android toast, needs no user interaction , goes away after period of time?
from searching around i'm seeing alerts need user clicks go away.
there simple solution this. using dependencyservice can toast-like approach in both android , ios.
create interface in common package.
public interface imessage { void longalert(string message); void shortalert(string message); } android section
[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 section
in ios there no native solution toast, need 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(); } } } } please note in each platform, have register our classes dependencyservice.
now can access out toast service in anywhere in our project.
dependencyservice.get<imessage>().shortalert(string message); dependencyservice.get<imessage>().longalert(string message);
Comments
Post a Comment