Recipe 2.7 Displaying Web Pages

Android Versions
Level 1 and above
Permissions
android.permission.INTERNET
Source Code to Download from Wrox.com
WebBrowser.zip

Oftentimes your Android application needs to load content from the web, such as images or web pages. This recipe shows you how to embed a web browser in your application and use it to load content from the web, as well as content stored locally in your application.

Solution

Assume you have the following code snippet in your activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/WebView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

The WebView element defines a web browser in your Android activity. You can use it to load content from the web or resources stored locally in your application.

The following code snippet shows how to load the WebView with an image from the web:

package net.learn2develop.webbrowser;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 WebView webView = (WebView) findViewById(R.id.WebView01); ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.