【发布时间】:2015-12-10 16:00:39
【问题描述】:
我是新来的,只是为了让大家知道。
我开始为 android 制作 webview 应用程序,我希望用户能够返回到上一页,而不是总是退出应用程序。
每当我运行应用程序并按返回图标时,我都会收到此运行时错误。
"System.NullReferenceException: 对象引用未设置为 对象的实例”
这段代码:
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && web_view.CanGoBack()) // <-- this is the line which brings up the error
{
web_view.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
我怀疑它与 WebView 有关。
谁能给我一些关于如何进行的建议?
下面是我的小项目的源代码:
using System;
using Android.App;
using Android.OS;
using Android.Webkit;
using Android.Views;
namespace MyWebApp
{
[Activity(Label = "MyWebApp", MainLauncher = true, Icon = "@drawable/icon", Theme = "@android:style/Theme.NoTitleBar")]
public class MainActivity : Activity
{
WebView web_view; //<-- I think this might be the issue?
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
DisplayWebpage(web_view, "http.google.com");
}
private WebView DisplayWebpage(WebView webview, String url)
{
webview = FindViewById<WebView>(Resource.Id.webView);
webview.Settings.JavaScriptEnabled = true;
webview.LoadUrl(url);
webview.SetWebViewClient(new WebView_Client());
return webview;
}
public class WebView_Client : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
}
// BACK FUNCTIONALITY
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && web_view.CanGoBack())
{
web_view.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
}
【问题讨论】:
标签: c# android webview xamarin