Object reference not set to an instance of an object while initializing WebView Xamarin Android

时间:2015-04-23 05:15:42

标签: android webview xamarin

I have the following code:-

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.layoutInformation);

    WebView Body = FindViewById<WebView>(Resource.Id.BodyContentWV);-- Error here

    // Create your application here
}

layoutInformation.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="25px"
    android:minHeight="25px">

    <android.webkit.WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/BodyContentWV" />

</LinearLayout>

I get the following error while initializing the WebView. Can anyone point out anything Iam doing wrong?

System.NullReferenceException: Object reference not set to an instance of an object

2 个答案:

答案 0 :(得分:1)

好的,我将尝试在我的代码中显示这一点,分为三点:

1)我有一个名为:ExtendedWebViewClient的类。它看起来像这样:

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

2)我有一个名为SearchWebActivity的Activity。它有资源xml文件和.cs文件。

a)资源xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/SearchWeb_WebView" />

b)SearchWebActivity的类.cs文件:

public class SearchWebActivity: Activity
{
    WebView _searchWeb_WebView;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.SearchWebActivity);
        _searchWeb_WebView= FindViewById<WebView>(Resource.Id.SearchWeb_WebView);

        setWebView();
    }

    private void setWebView()
    {
        _searchWeb_WebView.Settings.LoadWithOverviewMode = true;
        _searchWeb_WebView.Settings.UseWideViewPort = true;
        _searchWeb_WebView.Settings.BuiltInZoomControls = true;
        _searchWeb_WebView.Settings.JavaScriptEnabled = true;
        _searchWeb_WebView.ScrollbarFadingEnabled = false;
        _searchWeb_WebView.SetInitialScale(1);
        _searchWeb_WebView.SetWebViewClient(new ExtendedWebViewClient());

        _searchWeb_WebView.LoadUrl("www.google.com");
    }
}

希望它会有所帮助。

答案 1 :(得分:0)

Here:

 <android.webkit.WebView <<<< line
  ...
 />

android.webkit causing issue because package is Android.Webkit instead of android.webkit.

Simply use WebView for adding webview in xml:

 <WebView <<<< line
  ...
 />