Xamarin Forms: 在Android和IOS中使用Toast通知

3

你好,我正在使用PCL项目在Xamarin Forms中创建一个应用程序。我希望只在Android和iOS上实现双击后退时的Toast通知。对于Android,我尝试了-

long doublePressInterval_ms = 300;
DateTime lastPressTime = DateTime.MinValue;
DateTime pressTime = DateTime.Now;

        if ((pressTime - lastPressTime).TotalMilliseconds <= doublePressInterval_ms)
        {
            if(Device.OS == TargetPlatform.Android)
            {

                Java.Lang.JavaSystem.Exit(0);
            }
        }
        else
        {

           Android.Widget.Toast.MakeText(this, string_name, ToastLength.Long).Show();
        }
        lastPressTime = pressTime;
        return false;

但是它显示错误:无法将页面转换为Android上下文。我该如何在我的PCL项目中获取Android上下文?
我尝试过Xamarin的Toast通知插件,但它显示.Net版本不兼容。

enter image description here


2
可能是重复的问题Xamarin.Forms获取Android上下文 - SushiHangover
@SushiHangover,我尝试了所有提供的解决方案,但都没有解决问题。 - Sonali
Toast.MakeText(Xamarin.Forms.Forms.Context;, string_name, ToastLength.Long).Show(); - SushiHangover
@SushiHangover 我试过了,它说找不到 Xamarin.Forms.Forms.Context。 - Sonali
@SushiHangover 请参考截图。 - Sonali
5个回答

5
在 Xamarin Android 中,你可以像通常一样展示如下:
Toast.MakeText(this,"toast message", ToastLength.Long).Show();

在Xamarin iOS中,您需要使用自定义设计的UIView和动画来实现相同的效果。
public void ShowToast(String message, UIView view)
{
    UIView residualView = view.ViewWithTag(1989);
    if (residualView != null)
        residualView.RemoveFromSuperview();

    var viewBack = new UIView(new CoreGraphics.CGRect(83, 0, 300, 100));
    viewBack.BackgroundColor = UIColor.Black;
    viewBack.Tag = 1989;
    UILabel lblMsg = new UILabel(new CoreGraphics.CGRect(0, 20, 300, 60));
    lblMsg.Lines = 2;
    lblMsg.Text = message;
    lblMsg.TextColor = UIColor.White;
    lblMsg.TextAlignment = UITextAlignment.Center;
    viewBack.Center = view.Center;
    viewBack.AddSubview(lblMsg);
    view.AddSubview(viewBack);
    roundtheCorner(viewBack);
    UIView.BeginAnimations("Toast");
    UIView.SetAnimationDuration(3.0f);
    viewBack.Alpha = 0.0f;
    UIView.CommitAnimations();
}

1
这是最简单的解决方案,并且不会阻塞主UI。 - fatfatson
1
如何在iOS上设置UIView view参数? - VahidShir
只需在方法调用中传递视图引用即可。 - Durai Amuthan.H

3
您可以参考 Xamarin Forms的Toast通知,这里还有示例代码
基本上,它使用DependencyService在每个平台上实现ToastNotification,而每个平台都有自己的通知提示实现。
您可以按照指南完成工作,我遇到的唯一问题是安装此Toasts.Forms.Plugin。当您在PCL上安装此程序包时,可能会遇到以下异常:

Could not install package 'Toasts.Forms.Plugin 3.1.2'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259', but the package does not contain any assembly references or content files that are compatible with that framework.

为了解决此问题,您可以右键单击PCL并选择“卸载项目”,然后再次右键单击PCL并选择“编辑NAMESPACE.proj”,将代码<TargetFrameworkProfile>Profile259</TargetFrameworkProfile>替换为<TargetFrameworkProfile>Profile111</TargetFrameworkProfile>,保存此文件并重新加载此项目。更改此TargetFrameworkProfile后,此插件可以成功安装在PCL上。

1
public interface IToast
{
    void Message(string message);
}

[assembly: Xamarin.Forms.Dependency(typeof(STToast))]
namespace MasterDetail.Droid.Renderers
{
    public class STToast: IToast
    {
        public void Message(string message)
        {
            Toast.MakeText(Application.Context, message, ToastLength.Long).Show();
        }
    }
}

[assembly: Xamarin.Forms.Dependency(typeof(STToast))]
namespace MasterDetail.iOS.Renderers
{
    class STToast: IToast
    {
        const double LONG_DELAY = 3.5;
        const double SHORT_DELAY = 2.0;

        NSTimer alertDelay;
        UIAlertController alert;

        public void Message(string message)
        {
            ShowAlert(message, LONG_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();
            }
        }
    }
}

//MainPage
DependencyService.Get<IToast>().Message("Toast Message");

0

0

我使用了以下代码。演示在这里找到。

using Foundation;
using UIKit;`
using Xamarin.Forms;
using XamStart.Interfaces;
using XamStart.iOS.DependencyServices;
using XamStart.Models;

[assembly: Dependency(typeof(ToastService))]
namespace XamStart.iOS.DependencyServices
{
    public class ToastService : IToastService
    {
        // Code stolen from here:  http://sezeromer.com/xamarin-forms-ios-toast-mesaj/ 
        const double LONG_DELAY = 3.5;
        const double SHORT_DELAY = 2.0;

        NSTimer alertDelay;
        UIAlertController alert;
        public void CookIt(string message, MyToastLength length)
        {
            var toastLength = (length == MyToastLength.Long) ? LONG_DELAY : SHORT_DELAY;
            alertDelay = NSTimer.CreateRepeatingScheduledTimer(toastLength, (obj) =>
            {
                MesajReddet();
            });
            alert = UIAlertController.Create(null, message, UIAlertControllerStyle.Alert);

            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null);
        }

        void MesajReddet()
        {
            if (alert != null)
            {
                alert.DismissViewController(true, null);

            }
            if (alertDelay != null)
            {
                alertDelay.Dispose();
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接