Android WebViews are useful when you want to embed web pages into your applications. Its main purpose is showing specified web pages without need to open one of the installed web browsers. However, Android WebViews only show one URL and have no extra features as default. For example, if you click to one link from WebView, that link will not be opened in that webview; instead, it will be opened in one of the installed browsers. Of course, you can add additional features to your webviews if you need. In this tutorial, adding navigation back/forward will be explained.
First step: Adding WebView to your Application
First, you should add WebView element into your layout file. You can find detailed instructions fromhttp://developer.android.com/guide/webapps/webview.html#AddingWebView.
After adding WebView to layout file, if you want to access them in Java code, you can usefindViewByID() method in your Activity.
For example, let your WebView’s ID be “myWebView“. Then you can get it from your Activity class by:
Second step: Adding back/forward Menu Items
It is your design choise that where to add back/forward features.
For example you can add navigate back feature in the device’s back button by overriding “onKeyDown()” method which is explainedhttp://developer.android.com/guide/webapps/webview.html#HandlingNavigation.
But in this tutorial, this will be achieved by adding two menu items to the action bar. One menu item is going to be used for back and the other one is going to be used for forward navigation.
First you should create the menu (xml format) file of the Activity under the “src->res->menu” folder. In the menu file, you should define two menu items. Sample code is shown below:
Here, you can change icons with desired ones and you can change the menu item texts in the “strings.xml” file.
“android:showAsAction” makes the menu items visible on the action bar.
Third step: Handling Navigation Requests
In order to go back and forward in your WebView, just use “goBack()” and “goForward()” methods. It is so simple.
But before using these methods, you should be sure that they are applicaple by checking with “canGoBack()” and “canGoForward()” methods.
Because we are using menu items for navigation, we must handle menu item actions and use “goBack()” and “goForward()” methods in it. Sample code is shown below:
Some Important Notes:
- Don’t forget to add this permission to your manifest file. Without this, web page will not be loaded:
- By default WebView loads web pages without overview mode. So they are seen in full view mode. If you want them to be opened in overview mode just add these codes:
- By default there are no zoom in and out options in WebViews. If you want to use zoom options, just add this code:
- By default plugins (like Flash) will not work in WebViews. If you want to enable them, just add this code:
Comments
Post a Comment