How to display a web page inside an Android app? - Basics of WebView
If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView
. The WebView
class is an extension of Android’s View
class that allows you to display web pages as a part of your activity layout. It does not include any features of a fully developed web browser, such as navigation controls or an address bar. All that WebView
does, by default, is show a web page.
Using WebView
To add a WebView
to your Application, simply include the element in your activity layout. For example, here’s a layout file in which the WebView
fills the screen:
<WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="match_parent" />
To load a url in your app, just find the WebView
by id and use loadUrl().
WebView webView = (WebView) findViewById(R.id.web_view); webView.loadUrl("http://www.ghostcode.in");
Before you run the app, you have to ask for the INTERNET permission. You can do that in the manifest of your app. Just add the android.permission.INTERNET
<manifest ...> <uses-permission android:name="android.permission.INTERNET" /> ... </manifest>
Enabling JavaScript
JavaScript is disabled in a WebView
by default. You can enable it through the WebSettings attached to your WebView
. You can retrieve WebSettings with getSettings(), then enable JavaScript with setJavaScriptEnabled()
.
WebView webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true);
Handling Page Navigation
When the user clicks a link from a web page in your WebView
, the default behavior is for Android to launch an application that handles URLs. Usually, the default web browser opens and loads the destination URL. However, you can override this behavior for your WebView
, so links open within your WebView
. You can then allow the user to navigate backward and forward through their web page history that’s maintained by your WebView
.
To open links clicked by the user, simply provide a WebViewClient
for your WebView
, using setWebViewClient()
. For example:
WebView webView = (WebView) findViewById(R.id.web_view); webView.setWebViewClient(new WebViewClient());
That’s it. Now all links the user clicks load in your WebView
.
Here the final code for the WebView:
WebView webView = (WebView) findViewById(R.id.web_view); webView.setWebViewClient(new WebViewClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("http://www.ghostcode.in");