Pages

Tuesday 12 April 2011

First Steps (4) My Second Android Project

Extending a simple Android App to add a new WebView.Introducing: Activity, Intent, Layout, Manifest, WebView, UsesPermission

In this tutorial I will expand on my previous guide to building My First Android Project to add a new screen containing some web content You can continue from the code we had completed at the end of that project, which was a single Activity with a Button that invoked a Toast message. Alternatively you can start a new project and use this guide.

The aim of this second project is to add an additional Activity with a WebView control that displays a web page or HTML content. We will also have a look at the manifest file as we will require permission to access the web. Are you sitting comfortably?...

1. Open your MyAndroidProject project, or create a new project.

2. First we add a class that will be our new Activity. In Eclipse right-click on the project and select New > Class.



3. Complete the following information in the New Java Class form:

Source folder: MyAndroidProject/src
Package: com.androidelements.MyAndroidProject
The package namespace of our project.
Name: Web
The name of our new class.
Superclass: android.app.Activity
We are going to extend the Android Activity class.

Finally, untick the "Inherited abstract methods" tickbox so that we get an empty class definition and click on Finish.



4. The new activity will have been created inheriting from the Android Activity class, but without the onCreate method that is required for an activity. Copy and paste this from your Main.java activity or type in  the following so that the class is as below.

package com.androidelements.MyAndroidProject;

  import android.app.Activity;
  import android.os.Bundle;

  public class Web extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
   
  }

5. We need this activity to use a new layout, so ensure that the setContentView method is set to use a layout called "web":

    setContentView(R.layout.web);

6. The web layout does not yet exist so we need to create it by on the New Android XML File button in the menu:


7 Complete the New Android XML File wizard with the following information:

Project: MyAndroidProject
File: web.xml
What type of resource configuration would you like?: Layout
Folder: /res/layout
Select the root element for the XML file: LinearLayout

Click on the Finish button.


8. The web.xml will now be opened in the Graphical Layout view. Switch to the xml view by selecting the tab at the bottom of the screen labelled "web.xml".



9. Within the XML add a WebView. A view always requires a width and height. The values for these are one off fill_parent/match_parent (fill the space), wrap_content (use required space) or a fixed, defined size.

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <WebView
      android:id="@+id/web1"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
    </WebView>

  </LinearLayout>

Note the id specification, the @ (at) symbol denotes an id, and the + (plus) denotes that it should be added to the resource file (only supported on id declaration).

10. Save your new files and return to the Web.java code. You should see that the content setContentView declaration has a red warning underline under "web" of R.layout.web. This is because the resource file, R, has not been recompiled. To resolve this we need to 'clean' the project:



From the menu bar select Project > Clean...

11. In the Clean dialog, select "Clean projects selected below", tick the MyAndroidProject project, tick "Start a build immediately" and select "Build only the selected projects". Click OK.



After the clean has taken place the warning should be removed and the word "web" will display in italicised blue.

12. Now we want to add some code to set the contents of the web view. Add the following line under the setContentView method:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
       
        WebView web1 = (WebView)findViewById(R.id.web1);             
    }

This line defines a variable of type WebView and assigns it to the view in the layout by specifying the resource id as a parameter to the findviewById method.

13. Initially the words WebView will be underlined red because no reference to these object types exists in this Activity class. Hover your mouse cursor over the WebView keyword and a list of fixes will be displayed. Click on "Import 'WevView' (android.webkit).

This will add the following import reference to the top of your class (alternatively you can type this in yourself):

import android.webkit.WebView;

14. Now add a line to set the web view to display a web page:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
       
        WebView web1 = (WebView)findViewById(R.id.web1);
        web1.loadUrl("http://android-elements.blogspot.com/");
    }

15. Now we need to specify our new Activity and internet permission in the manifest. Open the Android.manifest file from the Package Explorer and switch to the XML view (bottom tab).

16. Add our new lines, the first defining the Activity and the second requesting internet access permission:

<?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.androidelements.MyAndroidProject"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Main"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Web" android:label="@string/app_name" />
    </application>
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>
17. Open the Main.java file. We are going to change our button click to launch the new Activity. This is done be creating a new Intent object, assigning a class name and then requesting the start of an activity:

package com.androidelements.MyAndroidProject;

  import android.app.Activity;
  import android.content.Intent;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Toast;

  public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
   
    public void clicked(View view) {
        Intent myIntent = new Intent();
        myIntent.setClassName("com.androidelements.MyAndroidProject", "com.androidelements.MyAndroidProject.Web");
        startActivity(myIntent);
    }
   
  }

18. Launch the AVD (Android Virtual Device) and run the app. You should see the screen with the single button. Click the button and you should see our new activity, wait a few seconds for the page to load and voila, you have a web page rendered within your app...

0 comments:

Post a Comment