WebView Template for Android SDK

android

 

 

 

 

If you’ve been trying to figure out how to setup a WebView with the Android SDK you may have quickly gotten frustrated with trying to find what you need online. While the information is out there, it’s not easy to find and it’s also not all in one place. So to help make things easier, I have build a WebView template with a collection of the most common controls that you would want to have enabled.

  • Zoom controls, with pinch to zoom
  • Double-tap zoom in/out controls

This tutorial is not meant to teach how to use Eclipse and the Android SDK, but it will show you how to setup the WebView. I have also included the source, which can be downloaded here: http://taiic.com/downloads

The first thing you need to do is create an Android project in Eclipse. If you want to make sure most devices will be able to use it, use the Android 1.6 (API level 4) for the project.

Ok, now that you have the blank project, there are a few items you need to consider.

  1. Application Icon
  2. Strings
  3. Layout

For the icon you need to use a .ico file and most image editing apps will have an option to save other image formats as .ico. In my template I also have a table view at the top of the screen with a logo which you’ll need another image file for if you want to replace. You can also just delete that part of the layout and let the WebView take up the entire screen. I’ll show you how to do this as well.

Application icon and other graphics

image

When you expand the project in Eclipse you will see the above folder structure. Under “res” there are three drawable folders, and each one represents a different screen size. It’s not required, but if you want to you can create different sizes of your images and place them in the appropriate folders. In general depending on what you’re doing, you can just delete the folders with –ldpi and –mdpi. You can always add them back if you want to add multiple screen support. You can get more info about multiple screen support here: http://developer.android.com/guide/practices/screens_support.html

Strings

Strings are used to create text that can be attached to various layout elements and display the string. So if you have a string with a value of “This is my application”, you can have a text label and when you define the properties for that label, you can reference this string and when viewed on your device you will see that string displayed where that label is. One of the beautiful things about using Eclipse with the Android SDK plugin, is that it offers a graphical interface to get an idea of what you will see on the device. It’s not perfect, but it’s better then nothing.

image

That is the view of the main.xml file that contains the layout where my application will show up. The logo is an image component that references an image file and the text references a string. Right below it you see the WebView component. By itself it’s just an empty space, but when we are done we will have an actual browser that starts in that space when opened on a device.

image

The image above is from my strings.xml file and as you can see it’s fairly straightforward. You have an entry with a Name and Value. The name is the ID of the string and the value is what it will show when referenced.

image

This is the same strings.xml file but in the xml view.

Layout

The layout file is the main.xml file. The graphical representation of which is above after the first paragraph in the Strings section. If you’ve been using Google App Inventor then this should look familiar to you. The reason is because the design view in App Inventor is basically an advanced version of the one in Android SDK. On the left you have various components that you can drag and drop on the design view. Keep in mind, that this view does not show an accurate representation of how it will look on the actual device, where as in App Inventor it tends to be 99% accurate. The layouts are built using xml and I’ll show you that piece in a bit.

Java

The last but certainly not least, piece of this puzzle is the .java file which is where the heart of the program is. This is where you write all the code that ties everything together and gives instructions to your application and how it works.

image

The .java file is located under the folder with the same name as your application package, which is inside the src folder.

Designing the Layout

So that’s a high level overview of an Android application. It barely touches the tip of the iceberg when it comes to Android apps, but in the scheme of things, you can build an entire application with just these minimum pieces. When you get into more complex apps that have multiple screens and many functions, you will find that there are multiple .java files, layout, strings, etc. If you want to get an idea for the complete folder structure that can be created, check out this page:
http://developer.android.com/guide/developing/projects/index.html

There are also some great tutorials on the Android developer site, if you want to see more examples. They provide source code as well, so you can always download and play around with it.

Tutorials
http://developer.android.com/resources/browser.html?tag=tutorial

Sample Code
http://developer.android.com/resources/browser.html?tag=sample

Ok, so lets take a look at the main.xml file and build the layout. For this tutorial, it really doesn’t get any simpler.

image

All you need to do is double-click main.xml to open it and then select the “Graphical Layout” tab at the bottom. Then under “Layouts”, drag out “LinearLayout” and under “Composite”, drag out the WebView component into the designer view on the right. That’s it, you know have a screen that is ready to display websites. Unfortunately it’s not as simple as App Inventor. The code still needs to be written, and we’ll get to that shortly.

If you click the tab on the right, “main.xml”, you will see the xml view.

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_height="wrap_content"
    android:layout_width="wrap_content"
    android:focusableInTouchMode="true">
WebView>    
LinearLayout>

I removed the XML portion for the additional stuff I have in my template. Take a look at the xml structure. XML is very logical and easy to understand from a design perspective. Every element type regardless of what the XML is for, has a start and end. In our tutorial we have two elements, the “LinearLayout” and the “WebView”. Each one has some basic elements already filled in for you. The “LinearLayout” orientation is set to vertical, and if it isn’t go ahead and change it so that it has the appropriate view in portrait. Set it’s width and height to “fill_parent”. The “WebView” component is contained within the “LinearLayout”. That is a simple procedure of placing one component before the closing tag of another, as seen here with “WebView”. What this does is make “WebView” inherit the layout properties of it’s parent component. So all you need to do for it is set it’s height and width to “wrap_content”. The other thing you need to do is give the “@+id” a name. Simply calling it webview is fine. You can call it whatever you want, but it’s a best practice to keep things logical so that they are easy to identify. This “id” is also what we will attach the WebView code to so that when the application starts this WebView component will actual fill the screen with a web browser.

Ok, now for the fun part. Open the .java file that I described earlier and add the following code right below the line “setContentView(R.layout.main);”

 myWebView = (WebView) findViewById(R.id.webview); // Create an instance of WebView and set it to the layout component created with id webview in main.xml
 myWebView.getSettings().setJavaScriptEnabled(true);
 myWebView.loadUrl("http://taiic.com"); // Specify the URL to load when the application starts
// myWebView.loadUrl("file://"); // Specify a local file to load when the application starts. Will only load file types WebView supports
 myWebView.setWebViewClient(new WebViewKeep());
 myWebView.setInitialScale(1); // Set the initial zoom scale
 myWebView.getSettings().setBuiltInZoomControls(true); // Initialize zoom controls for your WebView component
 myWebView.getSettings().setUseWideViewPort(true); // Initializes double-tap zoom control

I’ve added comments at the end of each line. When creating components you don’t use the actual component. What you do is create a variable that will inherit the functionality of the component and then using that variable you initialize various functions and perform actions with it.

If you look at the top of the source you will see where “myWebView” is initialized.

private WebView myWebView;

One other item that is out of scope here, but I’ll describe it since it is relevant. You can’t just simply reference a control and start coding. You need to tell the program where that control functionality can be found and this is done at the top of the file using “import”. For WebView I have the following.

import android.webkit.WebView;
import android.webkit.WebViewClient;

Once that is in the file you will be able to use those controls. One of the awesome things about development tools like Eclipse is a feature called “Content Assist”. The platform is designed to predict inherited functionality and give you advice and suggestions on what you need to do. So if you exclude the import and start coding the WebView functions, it will give you an error and a mouse-over on that particular error will give you an option to import the required component. It’s very cool. Unfortunately it’s not smart enough to do the bulk of the coding for you, but it makes a world of difference if you’re just starting out.

Ok, going back to that initial chunk of code, I wanted to go over the most important pieces that you will want to change to meet your needs.

myWebView.loadUrl("http://taiic.com");

I probably don’t have to explain this one. This is the URL that will load when your application starts. Change it to whatever URL you want.

myWebView.loadUrl("file://");

If you want to load a local file, you will use the same thing, except instead of http://, you use file:// and the path of the file. Keep in mind that you need to comment one of these out, you can’t have them both active. At least not the way this is designed. To comment out a single line, just precede it with two forward slashes //.

For example, I commented out the URL line and set the file to an image. The file path looks like this

myWebView.loadUrl(file://sdcard/DCIM/My Photos/Maui/Maui001.jpg);

And when I launch the app, I get…

photo

myWebView.setInitialScale(1);

The above line indicates the initial zoom level when your app starts. Setting it to 1 will fit almost any page into the device screen.

Those are the only things you need to change. Here are some of the other items in the code. Don’t make any changes to, I wanted to describe them so that you know what they are doing.

myWebView.getSettings().setBuiltInZoomControls(true);

This line enables pinch to zoom as well as a zoom control that appears on screen, as highlighted in the following screenshot.

screen

This control will show up as soon as you start dragging the screen.

myWebView.getSettings().setUseWideViewPort(true);

This enables double-tap zoom controls. I’m sure you’ve all used this. When you double-tap the screen, it will zoom in at that location. When you double-tap again, it will zoom out.

public boolean onKeyDown(int keyCode, KeyEvent event) {
   if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
       myWebView.goBack();
        return true;
   }
   return super.onKeyDown(keyCode, event);
}

The above lines of code enable the hardware back button to send the user back to the previous page. Without this, pressing that button will not do anything.

There you go, this brings together the most common controls you need for a basic WebView application. You can find the source on my download page. http://taiic.com/downloads

You may also like...

  • Pingback: Cmoneys Android Help Center - Android Apps - Best Android Apps, News and Reviews | Android-Apps.com()

  • sathish

    Hi ,

    Thanks for posting a great tutorial, it will be very useful.

    I have followed the things specified above to load a web app in my android webview and wants to fit into device screen size initially.But i am unable to get my requirement with my webview. If i try to open the same web app in device browser it is displaying like what i want(means fits into the device screen).

    Do i need any other settings for the webview to fit the web page in complete screen?

    Your help will be appreciated great.

    Thanks,
    sathish.

     

    • The line “myWebView.setInitialScare(1);” sets the zoom scale for the page when the app launches.

  • Dave

    Great tutorial thanks, I used it to build this 😀

    https://market.android.com/details?id=com.davidwcampbell.BBH

  • ישי מימון

     teank you ! 

  • Guest

    No one in their sane mind writes a programming tutorial that doesn’t let you copy the code -.- Good thing we have the web inspector…

    • The copy block is intended to protect the entire site. The fact that copying code in tutorials is impacted, is an unfortunate side effect.

      Second, if you look at the end of my tutorial, I always provide a link to where you can download the code. So I DO provide it.

      Lastly, how much credibility can you have if you don’t even post with your real name? 😉

  • Dude you should totally update this tutorial and make one with the latest sdk stuff..you’d be the only one with one. Google searching for a tutorial made in the past 6 months is eerily void of any up to date tuts. Thanks for providing this i’m going to give it a go even if it is old.

  • delter

    You can simply buy and use this cheap and ready codes for webview 😀 dont bother yourself to write it all.
    https://www.codester.com/items/1557/android-webview-application-template