You can use it to display things like help files , end-user agreements, FAQs etc. Since such contents change frequently, its useful to make a mobile friendly HTML webpage, and display them as a webpage rather than packaging them as part of your application.
Lets begin with a simple example that loads a URL from internet or local HTML file.
This is not much different from any of the previous examples we have seen. You have a simple WebView element that takes up the entire screen.
<?xml version="1.0" encoding="utf-8"?> <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/browser1" android:layout_width="match_parent" android:layout_height="match_parent"/>
In order for your application to access resources from the internet, you need to specify the Permission in the Android manifest file. Without this android wont let you load a URL from the internet.
<!--Specify the permissions that the application uses--> <uses-permission android:name="android.permission.INTERNET"/>
In addition to the loading a URL from the internet, you can also load resources local to your application. In this case we have a simple HTML page (HelloWorld.html) under the assets/html/ folder. You can access this local resource in your Java code by prefixing your URI (Uniform resource Identifier) with “file:///android_asset/<path-to-resource>” as shown later.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Hello World</title> </head> <body> <H1> Hi There...I am a local resource </H1> </body> </html>
Finally, within the activity class,
- We load the WebView element by its ID using the findViewById () method and
- Use a private helper method called loadResource() that can load both the URL and the local resource
Couple things to note here.
- If you want to load the local resource, simply call the private loadResource () method with the LOCAL_RESOURCE string instead of URL_TO_LOAD string .