Tips and Tricks for Android Users
Getting WebView To Load New Pages
There are a bunch of examples of using WebView to display HTML content loaded from the web in an Android app, including the sample from Google for the WebView class. However the ones I found generally don’t load new pages on their own. I can load up Google, but if you click on anything in the app it launches a browser and takes the user out of the app. The answer to the problem is in the additional points on that Hello, WebView page – you need to set a new WebViewClient to handle the URL load requests. Their example is very helpful, but I prefer to do the override with an anonymous inner class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webview.loadUrl("http://google.com");
setContentView(webview);
}
However, if you follow a link to an image it downloads instead of opens in the view. That’s the same thing the built in browser does, but wasn’t the behavior I expected. I’ll have to figure out how to handle that a bit better.
| Print article | This entry was posted by Lead Hacker on June 3, 2009 at 11:31 am, and is filed under Development. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |