Thursday, May 27, 2010

Android: WebView

= Display Loading Progress in Title Bar =

1. use Progress


step 1: enable extended window feature: FEATURE_PROGRESS
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.handle_config_change_in_webview);

step 2: implement WebChromeClient and overwrite function onProgressChanged
public void onProgressChanged(WebView view, int newProgress) {      
super.onProgressChanged(view, newProgress);
// newProgress (0-100), progress bar (0-10000)
setProgress(newProgress * 100);
}

step 3: set WebChromeClient to WebView by setWebChromeClient

2. use Indeterminate Progress


step 1: enable extended window feature: FEATURE_INDETERMINATE_PROGRESS
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.handle_config_change_in_webview);

step 2: implement WebViewClient and overwrite function onPageStarted, onPageFinished
public void onPageStarted(WebView view, String url, Bitmap favicon){  
setProgressBarIndeterminateVisibility(true);
}

public void onPageFinished(WebView view, String url){
setProgressBarIndeterminateVisibility(false);
}

step 3: set WebViewClient to WebView by setWebViewClient

= Handle Configuration Change =

Configuration changes (such as open/close hardware keyboard or change orientation) will trigger system to destroy your current activity, and then re-create a new instance of the activity.
When a configuration change occurs during WebView is loading a page, you might not want that system re-start this activity automatically since the loading procedure will be interrupted.
In this case, your activity need to handle configuration changes by itself.

To specify that kind of configuration changes your activity would like to handle, you must declare them by add "android:configChanges" attribute in manifest file.
<activity android:name="WebViewPractice" android:configChanges="keyboardHidden|orientation" android:label="Browser"></activity>


Then, your activity will receive a call to onConfigurationChanged() if configuration change occurs. A "Configuration" object is passed in for you to tell what kind of change occurs and to make appropriate changes by updating the resources if it is necessary.