gpt4 book ai didi

c# - Android C# WebView OnPageStart toast

转载 作者:行者123 更新时间:2023-11-29 20:25:08 24 4
gpt4 key购买 nike

我正在尝试在 WebView 启动时完成某种操作,例如加载纺车或 toast 消息...

我所做的会使应用程序崩溃。 (我是 C# 的新手,非常感谢简单的答案)。

public class MainActivity : Activity
{
private static Context context;

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);



// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);

WebView mWebView = FindViewById<WebView>(Resource.Id.webView);
mWebView.Settings.JavaScriptEnabled = true;

mWebView.SetWebViewClient(new MyWebViewClient());

//Load url to be randered on WebView
mWebView.LoadUrl("https://google.com");


}


public class MyWebViewClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}

public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
Toast.MakeText(context, "Loading...", ToastLength.Short).Show();
}

public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
}

public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
{
base.OnReceivedError(view, errorCode, description, failingUrl);
}
}
}

最佳答案

private static Context context; MainActivity 中的字段永远不会被赋值;在 Toast.MakeText(context ... ) 调用中使用它会导致空异常。使用全局上下文修复此问题:

Toast.MakeText(Android.App.Application.Context, "Loading...", ToastLength.Short).Show();

关于c# - Android C# WebView OnPageStart toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32660379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com