I am using Xamarin to write an Android application, and in that application, I have a webview that needs to load at the creation of the app and after it is fully loaded, I call some javascript into the HTML page to set up the graph.
I am trying to use a custom WebChromeClient
to override the OnProgressChanged
method, where when it fully loads, it calls a method in my MainActivity
.
Here is the MainActivity
code:
using System;
using System.Text;
using System.Timers;
using System.Collections;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Text;
using Android.Text.Style;
using Android.Webkit;
public class MainActivity : Activity
{
WebView graph;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
graph = FindViewById<WebView>(Resource.Id.webGraph);
//Initializes the WebView
graph.SetWebChromeClient(new myWebChromeClient());
graph.Settings.JavaScriptEnabled = true;
graph.LoadUrl("file:///android_asset/graph.html");
And the myWebChromeClient
class I created looks like this:
class myWebChromeClient : WebChromeClient
{
public override void OnProgressChanged(WebView view, int newProgress)
{
base.OnProgressChanged(view, newProgress);
if (newProgress == 100) {MainActivity.setUpGraph();}
}
}
The myWebChromeClient
is within the MainActivity
, but I am unable to access the setUpGraph
method even though it is a public method.
Any help will be appreciated!
Accept and store a reference of type MainActivity in myWebChromeClient class. Only then can you call the setUpGraph() function in MainActivity.
EDIT
The myWebChromeClient class:
class myWebChromeClient : WebChromeClient
{
public MainActivity activity;
public override void OnProgressChanged(WebView view, int newProgress)
{
base.OnProgressChanged(view, newProgress);
if (newProgress == 100) { activity.setUpGraph(); }
}
}
And the activity:
public class MainActivity : Activity
{
WebView graph;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
graph = FindViewById<WebView>(Resource.Id.webGraph);
//Initializes the WebView
myWebChromeClient client = new myWebChromeClient();
client.activity = this;
graph.SetWebChromeClient(client);
graph.Settings.JavaScriptEnabled = true;
graph.LoadUrl("file:///android_asset/graph.html");
For the sake of simplicity, I've added a public variable to the client, please don't use the same in production. Pass the reference in a constructor or use get-set.