Android WebView Tutorial
|
|
The WebView enables us to embed a web browser in our activity. It uses the WebKit rendering engine to display web pages. It is very useful to display some online/offline web contents within our activity. So in this tutorial we will learn about how to display some online/offline web contents within our activity using WebView.
First create new Android SDK project in eclipse or your IDE of choice. You can name the main activity, package and project anything you want.
Open the layout file & then add a WebView, assign an ID so you can access the widget later.
Since we’re going to load a URL in the WebView widget, we have to make sure to request permission to access the Internet in AndroidManifest.xml. Open AndroidManifest.xml file and declare a uses-permission element just above <application> ... </application> element.
Open up your main activity and add the following code into the onCreate() method:
The above code accesses the WebView widget via its resource ID and invokes loadUrl() method. Start the app in the emulator and view the result: it should display the site you’re currently on!
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().
(Note: Add it just below the code in step 4)
To display the built-in zoom controls, you need to first get the WebSettings property from the WebView & then call its setBuiltInZoomControls() method.
(Note: Add it just before the code in step 5)
When you clicks a link from a web page in your WebView, it will cause your application to launch the browser application to load the desired page. 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().
That's it. Now all links the user clicks load in your WebView. If you want more control over where a clicked link load, create your own WebViewClient that overrides the shouldOverrideUrlLoading() method.
If you are going to create your own WebViewClient then you also need to assign it to your WebView as:
Whenever the user press the BACK button the activity that handles the WebView is closed. If you want to use BACK button to navigate from current opened link to previously opened link in WebView then you need to override the onKeyDown() inside the activity.
The condition uses a KeyEvent to check whether the key pressed is the BACK button and whether the WebView is actually capable of navigating back (if it has a history). If both are not true, then it send the event up the chain (and the Activity will close). But if both are true, then it call goBack(), which will navigate back one step in the history. You can also navigate forward through the history with goForward() method.
You can also dynamically formulate an HTML string & load it into the WebView, using the loadData() method. It takes three arguments:
Step 1: Setting up the project
First create new Android SDK project in eclipse or your IDE of choice. You can name the main activity, package and project anything you want.
Step 2: Setting up the WebView Widget
Open the layout file & then add a WebView, assign an ID so you can access the widget later.
<?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">
<WebView android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Step 3: Requesting Internet Permission (Android Manifest)
Since we’re going to load a URL in the WebView widget, we have to make sure to request permission to access the Internet in AndroidManifest.xml. Open AndroidManifest.xml file and declare a uses-permission element just above <application> ... </application> element.
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Loading a Web Page
Open up your main activity and add the following code into the onCreate() method:
WebView mywebview = (WebView) findViewById(R.id.webview);
mywebview.loadUrl("http://www.androidaspect.com/?m=1");
mywebview.loadUrl("http://www.androidaspect.com/?m=1");
The above code accesses the WebView widget via its resource ID and invokes loadUrl() method. Start the app in the emulator and view the result: it should display the site you’re currently on!
Step 5: 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().
WebSettings webSettings = mywebview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptEnabled(true);
(Note: Add it just below the code in step 4)
Step 6: Built-in Zoom Controls
To display the built-in zoom controls, you need to first get the WebSettings property from the WebView & then call its setBuiltInZoomControls() method.
webSettings.setBuiltInZoomControls(true);
(Note: Add it just before the code in step 5)
Step 7: Handling Page Navigation
When you clicks a link from a web page in your WebView, it will cause your application to launch the browser application to load the desired page. 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().
mywebview.setWebViewClient(new WebViewClient());
That's it. Now all links the user clicks load in your WebView. If you want more control over where a clicked link load, create your own WebViewClient that overrides the shouldOverrideUrlLoading() method.
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
If you are going to create your own WebViewClient then you also need to assign it to your WebView as:
mywebview.setWebViewClient(new MyWebViewClient());
Step 8: Handling the Back Button Key Press
Whenever the user press the BACK button the activity that handles the WebView is closed. If you want to use BACK button to navigate from current opened link to previously opened link in WebView then you need to override the onKeyDown() inside the activity.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
mywebview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
mywebview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
The condition uses a KeyEvent to check whether the key pressed is the BACK button and whether the WebView is actually capable of navigating back (if it has a history). If both are not true, then it send the event up the chain (and the Activity will close). But if both are true, then it call goBack(), which will navigate back one step in the history. You can also navigate forward through the history with goForward() method.
Step 9: Rendering Custom Markup
You can also dynamically formulate an HTML string & load it into the WebView, using the loadData() method. It takes three arguments:
- String htmlData
- String mimeType
- String encoding
String data = "<html>" +
"<body><h1>Hello, Android Aspect!</h1></body>" +
"</html>";
mywebview.loadData(data, "text/html", "UTF-8");
"<body><h1>Hello, Android Aspect!</h1></body>" +
"</html>";
mywebview.loadData(data, "text/html", "UTF-8");
Now Restart the app in the emulator and view the result: you should see this:
Alternatively, You can also create your own HTML file & save it in assets folder, you can also load it into the WebView using the loadUrl() method.
First create a "hello.html" file & save it into assets folder.
<Body bgcolor="Green">
<H1>Hello HTML</H1>
<font color="yellow">WebView Tutorial by Android Aspect</font>
</Body>
<H1>Hello HTML</H1>
<font color="yellow">WebView Tutorial by Android Aspect</font>
</Body>
Comment out the mywebview.loadData() line and insert the following code:
mywebview.loadUrl("file:///android_asset/hello.html");
Now Restart the app in the emulator and view the result: you should see this:











nice tutorial
really useful, thanks :)
thank you very much.save my tiime
Thanks for the simple code.
Very useful for beginners. Thanks.
Great article...
Thank You Very Much
Many thanks
Post a Comment