【发布时间】:2018-04-08 06:25:08
【问题描述】:
我正在使用 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
}
}
这是 Strings.xml 中 LblExportMsg 的值:
<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 进行反序列化。
【问题讨论】:
-
请分享你的js代码。
-
嗨@YorkShen-MSFT,它就在那里,这就是我调用该方法的方式:CSharp.ExportToExcel("");,没什么特别的,我只是共享了一个 JSON 而不是空字符串,它完全正常工作,因为它成功导出了 excel。谢谢。
-
我无法重现您的问题,因此请分享一个基本演示或更完整的代码,以便我们可以重现此问题。
-
没问题@YorkShen-MSFT,我添加了更多代码和我期待的 JSON 示例
-
这很奇怪,它应该可以工作。您介意分享一个可以通过在线存储库重现此问题的基本演示吗?
标签: javascript c# android xamarin.android android-toast