Android 带进度条的WebView(Kotlin)

自定义WebView



import android.annotation.SuppressLint
import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.webkit.*
import android.widget.ProgressBar


class MyWebView constructor(context: Context, attributeset: AttributeSet) : ConstraintLayout(context, attributeset) {

    private var progress: ProgressBar
    private var webview: WebView
    private var isLastLoadSuccess = false//是否成功加载完成过web,成功过后的网络异常 不改变web
    private var isError = false

    init {
        val 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.webChromeClient = MyWebChromeClient()
        webview.webViewClient = MyWebViewClient()
        webview.settings.setJavaScriptEnabled(true)
        webview.settings.cacheMode = WebSettings.LOAD_NO_CACHE
    }

    private inner class MyWebChromeClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            setProgress(newProgress)
        }

        override fun onReceivedTitle(view: WebView, title: String) {
            super.onReceivedTitle(view, title)
            if (title.contains("html")) {
                return
            }
            listener?.onTitle(title)
        }
    }

    private fun setProgress(newProgress: Int) {
        if (newProgress == 100) {
            progress.visibility = View.GONE
        } else {
            progress.progress = newProgress
        }
    }

    private inner class MyWebViewClient : WebViewClient() {

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            //在访问失败的时候会首先回调onReceivedError,然后再回调onPageFinished。
            if (!isError) {
                isLastLoadSuccess = true
                listener?.success()
            }
        }

        override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
            super.onReceivedError(view, request, error)
            //在访问失败的时候会首先回调onReceivedError,然后再回调onPageFinished。
            isError = true
            if (!isLastLoadSuccess) {//之前成功加载完成过,不会回调
                listener?.error()
            }
        }
    }

    /**
     * 千万不要更改这个 "SSDJsBirdge"  注意!!!!!
     */
    @SuppressLint("JavascriptInterface")
    fun addJavascriptInterface(jsInterface: Any) {
        webview.addJavascriptInterface(jsInterface, "SSDJsBirdge")
    }

    fun reload() {
        isError = false
        webview.reload()
    }

    fun loadUrl(url: String) {
        isError = false
        try {
            webview.loadUrl(url)
        } catch (e: Exception) {

        }

    }

    fun canGoBack(): Boolean {
        val canGoBack = webview.canGoBack()
        if (canGoBack) {
            webview.goBack()
        }
        return canGoBack
    }

    /**
     * must be called on the main thread
     */
    fun destory() {
        try {
            webview.destroy()
        } catch (e: Exception) {
        }

    }

    private var listener: OnWebLoadStatusListener? = null

    fun setOnLoadStatueListener(listener: OnWebLoadStatusListener) {
        this.listener = listener
    }

    interface OnWebLoadStatusListener {
        fun error()

        fun success()

        fun onTitle(title: String)
    }
}

XML文件 : layout_web_progress_view

<?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:progressDrawable="@drawable/progress_bg">
    </ProgressBar>

    <WebView
        android:id="@+id/my_web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
</LinearLayout>

进度条样式  drawable progress_bg

<?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="15dp"/>
            <solid android:color="#e5e6e7"></solid>
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="15dp"/>
                <solid android:color="#00abff"></solid>
            </shape>
        </clip>
    </item>

</layer-list>

Activity中使用

class CommonWebActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_common_web)
        web_view.setOnLoadStatueListener(object : MyWebView.OnWebLoadStatusListener {
            override fun error() {
                empty_view.setEmptyImage(R.drawable.load_fail)
                empty_view.setEmptyText(R.string.net_error_again)
            }

            override fun success() {
                empty_view.setGone()
            }

            override fun onTitle(title: String) {
                tv_title.text = title
            }

        })
        web_view.loadUrl("https://www.hao123.com/?1556417874")
    }
}

猜你喜欢

转载自blog.csdn.net/Leo_Liang_jie/article/details/83001696