1. 程式人生 > >Android 帶進度條的WebView

Android 帶進度條的WebView

自定義帶進度條的WebView,

【-------------------xml 檔案------------------------】
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp2"
        style="?android:attr/progressBarStyleHorizontal"
        android:background="@drawable/progress_bg">
    </ProgressBar>

    <WebView
        android:id="@+id/my_web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
</LinearLayout>
【-------------------progress_bg.xml------------------------】
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="@dimen/dp15" />
            <solid android:color="@color/color_f2f2f2"></solid>
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="@dimen/dp15" />
                <solid android:color="@color/color_f57e5c"></solid>
            </shape>
        </clip>
    </item>

</layer-list>
【-------------------自定義webview------------------------】

public class MyWebProgressView extends FrameLayout {
    private final static String TAG = MyWebProgressView.class.getSimpleName();

    private ProgressBar progress;
    private WebView webview;
    private View rootView;


    private boolean isLastLoadSuccess = false;//是否成功載入完成過web,成功過後的網路異常 不改變web
    private boolean isError = false;

    public MyWebProgressView(Context context) {
        super(context);
        initiView(context);
    }

    public MyWebProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initiView(context);
    }

    public MyWebProgressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initiView(context);
    }


    private void initiView(Context context) {
        rootView = LayoutInflater.from(context).inflate(R.layout.layout_web_progress_view, this, true);
        progress = rootView.findViewById(R.id.progress);
        webview = rootView.findViewById(R.id.my_web_view);
        webview.setWebChromeClient(new MyWebChromeClient());
        webview.setWebViewClient(new MyWebViewClient());
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    private class MyWebChromeClient extends WebChromeClient{

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            LogUtils.d(TAG,"onProgressChanged newProgress : " + newProgress);
            setProgress(newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (title.contains("html")){
                return;
            }
            listener.onTitle(title);
        }
    }

    private void setProgress(int newProgress) {
        if (newProgress == 100){
            progress.setVisibility(View.GONE);
        }else {
            progress.setProgress(newProgress);
        }
    }

    private class MyWebViewClient extends WebViewClient{

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            LogUtils.d(TAG,"MyWebViewClient onPageFinished ");
            //在訪問失敗的時候會首先回調onReceivedError,然後再回調onPageFinished。
            if (!isError){
                isLastLoadSuccess = true;
                listener.success();
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            LogUtils.d(TAG,"MyWebViewClient onReceivedError ");
            //在訪問失敗的時候會首先回調onReceivedError,然後再回調onPageFinished。
            isError = true;
            if (!isLastLoadSuccess){//之前成功載入完成過,不會回撥
                listener.error();
            }
        }
    }


    @SuppressLint("JavascriptInterface")
    public void addJavascriptInterface(Object jsInterface){
        //千萬不要更改這個 "control"  注意!!!!!
        webview.addJavascriptInterface(jsInterface, "control");
    }

    public void reload(){
        isError = false;
        webview.reload();
    }

    public void loadUrl(String url){
        isError = false;
        try {
            webview.loadUrl(url);
        }catch (Exception e){
            LogUtils.d(TAG,"loadUrl 出異常: " + e.getMessage());
        }
    }

    public boolean canGoBack(){
        boolean canGoBack = webview.canGoBack();
        if (canGoBack){
            webview.goBack();
        }
        return canGoBack;
    }

    /*
    * must be called on the main thread
    * */
    public void destory(){
        try {
            webview.destroy();
        }catch (Exception e){
            LogUtils.d(TAG,"destory 出異常: " + e.getMessage());
        }
    }

    private OnWebLoadStatusListener listener;

    public void setOnLoadStatueListener(OnWebLoadStatusListener listener){
        this.listener = listener;
    }
    public interface OnWebLoadStatusListener {
        void error();
        void success();
        void onTitle(String title);
    }
}

【------------------Activity呼叫------------------------】

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rule_detail);
    final MyWebProgressView webView = findViewById(R.id.webview);
    webView.setOnLoadStatueListener(new MyWebProgressView.OnWebLoadStatusListener() {
          @Override
         public void error() {
              
         }

          @Override
         public void success() {
              
         }

          @Override
         public void onTitle(String title) {
              
         }
   });
}