Android/webview/上部固定式loading
ナビゲーションに移動
検索に移動
サンプル
- layout/webview.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ProgressBar android:id="@+id/ProgressBarHorizontal" android:layout_width="fill_parent" android:layout_height="2dip" style="?android:attr/progressBarStyleHorizontal" /> <WebView android:id="@+id/webview1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout>
- WebviewActivity.java
setContentView(R.layout.webview);
mWebView = (WebView) findViewById(R.id.webview1);
mProgressBar = (ProgressBar) findViewById(R.id.ProgressBarHorizontal);
CustomWebView CustomWebView = new CustomWebView(getApplicationContext());
CustomWebView.setWebView(mWebView);
CustomWebView.setProgressBar(mProgressBar);
String url = getResources().getString(R.string.top_url);
CustomWebView.setUrl(url);
CustomWebView.load();
- CustomWebView.java
import android.widget.ProgressBar;
public class CustomWebView {
private Context mContext;
private WebView mWebView;
private ProgressDialog mProgress;
private ProgressBar mProgressBar;
public CustomWebView(Context context) {
mContext = context;
}
// WebView指定
public void setWebView(WebView webView) {
mWebView = webView;
mWebView.setWebViewClient(new CustomWebViewClient());
mWebView.setWebChromeClient(new CustomWebChromeClient());
}
public void setProgressBar(ProgressBar progressBar) {
mProgressBar = progressBar;
mProgressBar.setMax(100); // 水平プログレスバーの最大値を設定
}
// 解放
public void release() {
mWebView = null;
mContext = null;
}
// NowLoadingクラス
private class CustomWebViewClient extends WebViewClient {
public CustomWebViewClient(){
super();
mProgress = null;
}
// ページ表示開始イベント
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (mProgressBar != null) {
mProgressBar.setProgress(0); // 水平プログレスバーの値を設定
}
}
// ページ表示終了イベント
public void onPageFinished(WebView view, String url){
if (mProgressBar != null) {
mProgressBar.setProgress(0); // 水平プログレスバーの値を設定
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (mProgressBar != null) {
mProgressBar.setProgress(0); // 水平プログレスバーの値を設定
}
}
}
private class CustomWebChromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int progress) {
if (mProgressBar != null) {
// 50%以上進んだら進捗ダイアログを閉じる(早めに閉じて見た目を高速化させる
if (progress > 50) {
mProgressBar.setProgress(0); // 水平プログレスバーの値を設定
} else {
mProgressBar.setProgress(progress); // 水平プログレスバーの値を設定
}
}
}
}
}