2013/04/11

WebView with Progressbar

在 WebView 加上 progressbar 讓使用者知道目前載入進度,

主要利用 WebViewClient 和 WebChromeClient

WebViewClient 可以知道載入開始和載入結束, 可用來判斷是否該顯示 ProgressBar 或者該隱藏
WebChromeClient 可用來知道載入進度

Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ProgressBar
android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:indeterminate="true"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_alignParentBottom="true" 
android:visibility="gone"/>

<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/progress" />

</RelativeLayout>

主程式碼
package tw.clotai.webviewexample;

import tw.clotai.webviewexample.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

WebView mWebView = null;
ProgressBar mBar = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mWebView = (WebView)findViewById(R.id.webview);
mBar = (ProgressBar)findViewById(R.id.progress);

mWebView.setWebViewClient(mWebViewClient);
mWebView.setWebChromeClient(mWebChromeClient);
mWebView.loadUrl("http://tw.yahoo.com");
//mWebView.loadUrl("file:///android_asset/example.html");
}

WebViewClient mWebViewClient = new WebViewClient() {

@Override
public void onPageFinished(WebView view, String url) {
mBar.setVisibility(View.GONE);
}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mBar.setVisibility(View.VISIBLE);
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
};

WebChromeClient mWebChromeClient = new WebChromeClient() {

@Override
public void onProgressChanged(WebView view, int newProgress) {
mBar.setIndeterminate(false);
mBar.setProgress(newProgress);
}

@Override
public void onReceivedTitle(WebView view, String title) {
if ((title != null) && (title.trim().length() != 0)) {
setTitle(title);
}
}
};
}




原始碼: WebViewExample_2

參考:
[1] 基本使用 webview