Friday, March 13, 2009

android web applications seamlessly integrate native widgets

I'm writing some android sample code to be included in training courses and I found this example so interesting that I decided to publish it here to share it with you. I hope you find it interesting too.

This example is extremely simple, just a few lines of code, but demonstrates how powerful the idea of mixing native widgets and web applications can be.

The application consists of an oversimplified web browser based on WebView and a super imposed SeekBar slider that when is moved changes the background color of the page using javascript. The default page is http://google.com to demonstrate that no special javascript code is needed in the page.




Views hierarchy
This is how we defined the layout.



Basically, the idea is to have a RelativeLayout holding the WebView and the SeekBar over it.

Changing the background color

This is the most interesting part, in the SeekBar change listener we will be invoking the javascript needed to change the page background color using the DOM. Also we will be using a simple conversion from the progress value to HSV colors.
To invoke the javascript we use webView.loadUrl.







// change color depending on seek bar position
colorBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
float p100 = progress / 100.0f;
webView.loadUrl(String.format(
"javascript:{document.body.style.backgroundColor='#%06x'}",
Color.HSVToColor(new float[] {360 * p100, p100, 1 - p100 }) &
OPAQUE));

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

});



Seamless applications
One of the main objectives of the android platform is to provide a seamless experience to the user. In this case we have seen how to seamlessly integrate native and web applications.

Installing the application
To install Android Web Page Background Color Bridge into your phone or emulator visit http://codtech.com/downloads/android directly from the device providing you have an SD card to download it and the required permission enable to install application from Unknown Sources in Settings.

Source code
Source code can also be downloaded from http://codtech.com/downloads/android

No comments: