Make sure you have your
Android development environment setup and ready to go. Create a new Android project in Eclipse and name it whatever you wish. I named mine “WebPageLoader”.
You’ll notice I am targeting Android 1.6 and above, feel free to
target newer SDK versions if you wish. The first thing we need to do is
modify the “main.xml” file located in the “res/layout” folder.
Overwrite the existing code with this:
<? xml version = "1.0" encoding = "utf-8" ?>
< WebView xmlns:android = "http://schemas.android.com/apk/res/android"
android:id = "@+id/webview"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
/>
|
Now go into the “AndroidManifest.xml” file and add the following line:
< uses-permission android:name = "android.permission.INTERNET" />
|
That line is required because we will be using the Internet therefore we need to have the appropriate permissions set.
Go back into the “WebPageLoader.java” file and paste in this code overwriting the existing code:
package com.giantflyingsaucer;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
final Activity activity = this ;
@Override
public void onCreate(Bundle savedInstanceState)
{
super .onCreate(savedInstanceState);
this .getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled( true );
webView.setWebChromeClient( new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle( "Loading..." );
activity.setProgress(progress * 100 );
if (progress == 100 )
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient( new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true ;
}
});
webView.loadUrl( "http://developer.android.com" );
}
}
|
The code is pretty simple. It loads a webpage, shows the progression of loading the website, etc.