Thứ Sáu, 5 tháng 8, 2011

Load WebView with ProgressDialog


It’s very useful to determine the status while loading a web page. Here a sample to showProgressDialog to track when WebVIew done with loading URL.


public class MainActivity extends Activity {
WebView mWeb;
ProgressDialog mProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// no need to use title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
// set webview as main content only
mWeb = new WebView(this);
setContentView(mWeb);
// set Javascript
WebSettings settings = mWeb.getSettings();
settings.setJavaScriptEnabled(true);
// the init state of progress dialog
mProgress = ProgressDialog.show(this, "Loading", "Please wait for a moment...");
// add a WebViewClient for WebView, which actually handles loading data from web
mWeb.setWebViewClient(new WebViewClient() {
// load url
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
// when finish loading page
public void onPageFinished(WebView view, String url) {
if(mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
// set url for webview to load
mWeb.loadUrl("http://www.cnn.com");
}
}

0 nhận xét: