Yes, you can use Xamarin.Forms DependencyService to achieve this .
Please refer to the following code:
1.create interface IToast
in forms:
public interface IToast
{
void Show(string message);
}
2.In android, create class Toast_Android
to inplement interface IToast
and set gravity to GravityFlags.Top
:
[assembly: Xamarin.Forms.Dependency(typeof(Toast_Android))]
namespace ToastApp.Droid
{
public class Toast_Android : IToast
{
public void Show(string message)
{
Toast toast = Toast.MakeText(Android.App.Application.Context, message, ToastLength.Long);
View view = toast.View;
view.SetBackgroundColor(Color.Yellow);
TextView text = (TextView)view.FindViewById(Android.Resource.Id.Message);
text.SetTextColor(Color.Red);
toast.SetGravity(GravityFlags.Top, 0, 0);
toast.Show();
}
}
}
Note:
3.In ios, create class Toast_IOS
to inplement interface IToast and set the postion of the view:
[assembly: Xamarin.Forms.Dependency(typeof(Toast_IOS))]
namespace ToastApp.iOS
{
public class Toast_IOS : IToast
{
const double LONG_DELAY = 3.5;
NSTimer alertDelay;
UIViewController alert;
const float DialogWith = 160;
public void Show(string message)
{
ShowAlert(message, LONG_DELAY);
}
void ShowAlert(string message, double seconds)
{
alertDelay = NSTimer.CreateScheduledTimer(seconds, (obj) =>
{
dismissMessage();
});
alert = new UIViewController();
UILabel view = new UILabel();
int DeviceWidth = (int)UIScreen.MainScreen.Bounds.Width;
float position = (DeviceWidth - DialogWith) / 2;
view.Frame = new CoreGraphics.CGRect(position, 0, DialogWith, 100);
view.Text = message;
// you can customize the style as you want
view.TextColor = UIColor.Red;
view.BackgroundColor = UIColor.Yellow;
alert.View.Add(view);
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
}
void dismissMessage()
{
if (alert != null)
{
alert.DismissViewController(true,null);
}
if (alertDelay != null)
{
alertDelay.Dispose();
}
}
}
}