Android Tutorial

(avery) #1
Android Tutorial 387


  1. Load your content into the WebView control using one of the standard
    methods, such as the loadUrl() method. In this case, we load an HTML
    asset we defined within the application package.


If you followed these steps, you should end up with your activity’s
onCreate() method looking something like this:


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final WebView wv = (WebView) findViewById(R.id.html_viewer);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
WebChromeClient webChrome = new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
Log.v(DEBUG_TAG, consoleMessage.lineNumber()



  • “: “ + consoleMessage.message());
    return true;
    }
    };
    wv.setWebChromeClient(webChrome);
    wv.addJavascriptInterface(new JavaScriptExtensions(), “jse”);
    wv.loadUrl(“file:///android_asset/sample.html”);
    }


A custom WebChromeClient class is set so that any JavaScript
console.log messages go out to LogCat output, using a custom
debug tag as usual to enable easy tracking of log output specific to
the application. Next, a new JavaScript interface is defined with the
namespace called jse—the namespace is up to you. To call from
JavaScript to this Java class, the JavaScript calls must all start with
namespace jse., followed by the appropriate exposed method—for
instance, jse.javaMethod().

Free download pdf