代码之家  ›  专栏  ›  技术社区  ›  Federico Navarrete

Toast通知在JavaScript调用上不起作用

  •  1
  • Federico Navarrete  · 技术社区  · 7 年前

    我正在与Xamarin开发一个应用程序。Android和我想在从JavaScript导出报告时显示Toast通知。我的应用程序调用该报告并成功生成。但是,不会显示Toast通知。我发现,只有在该特定行中设置断点时,它才会显示在Visual Studio 2017中。

    这是我处理JS的C#类的一部分。

    class CallJSInterface : Java.Lang.Object
    {
        private class Timetable
        {
            public string member { get; set; }
            public string role { get; set; }
            public string time { get; set; }
            public string lastColor { get; set; }
        }
    
        private Context context;
        public CallJSInterface(Context context)
        {
            this.context = context;
        }
    
        [Export]
        [JavascriptInterface]
        public void ExportToExcel(string results)
        {
            Toast.MakeText(context, context.GetString(Resource.String.LblExportMsg), ToastLength.Short).Show();
    
            var timetable = JsonConvert.DeserializeObject<List<Timetable>>(results);
    
            //Excel conversion
        }
    }
    

    这是 LblExportMsg 在字符串中。xml:

    <string name="LblExportMsg">Exporting your Agenda to Excel.</string>
    

    此外,这是我在JS中调用函数的一个示例:

    $("#linkDownload").click(function (e) {
        e.preventDefault();
        CSharp.ExportToExcel('[{"member":"Luis","role":"Timer","time":"00:15:15","lastColor":"red"},{"member":"Luis","role":"Timer 1","time":"00:15:00","lastColor":"green"},{"member":"Luis","role":"Timer 2","time":"00:15:17","lastColor":"red"},{"member":"Luis","role":"Timer 3","time":"00:07:15","lastColor":"green"},{"member":"Luis","role":"Timer 4","time":"00:23:15","lastColor":"red"},{"member":"Luis","role":"Timer 5","time":"00:15:15","lastColor":"green"},{"member":"Luis","role":"Timer 6","time":"01:15:15","lastColor":"yellow"},{"member":"Luis","role":"Timer 7","time":"00:18:15","lastColor":"green"},{"member":"Luis","role":"Timer 8","time":"00:15:22","lastColor":"green"}]');
    });
    

    此外,HTML按钮:

    <button type="button" id="linkDownload">Export</button>
    

    最后,这是我如何将JS接口从主活动添加到WebView的:

    webView.AddJavascriptInterface(new CallJSInterface(this), "CSharp");
    

    有人知道我做错了什么吗?这与上下文有关吗?我如何检查它?谢谢你的帮助。

    PS:

    • 最小SDK为21,目标SDK为27。
    • 我正在使用 JSON.NET 用于反序列化。
    1 回复  |  直到 7 年前
        1
  •  3
  •   Federico Navarrete    7 年前

    我能够修复它,我在导出报告之前添加了一个超时,并且将过程一分为二,一个用于显示Toast,另一个用于报告。

    $("#linkDownload").click(function (e) {
        CSharp.Alert(currentTranslation.lblExportMsg);
        setTimeout(function () {
            CSharp.ExportToExcel(JSON.stringify(results));
        }, 250);
    });