How to Replace Webpage Not Available Page To Custom Page? (WEBVIEW)

前端 未结 2 1026
再見小時候
再見小時候 2021-01-06 17:37

I want to change page from Webpage not Available or ERR_NAME_NOT_RESOLVED

to My Page \"No Internet Connection\"?

a

相关标签:
2条回答
  • 2021-01-06 18:10

    Replace default WebChromeClient with your custom CustomWebviewClient as below

    webView!!.setWebViewClient(object : CustomWebviewClient()
    

    then create this custom WebViewClient

        inner class CustomWebviewClient : WebViewClient() {
    
        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
            super.onPageStarted(view, url, favicon)
        }
    
        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
        }
    
        override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
            super.onReceivedError(view, request, error)
    
            if (noInternetConnection()) {
                loadNoInternetErrorView()
            } else {
                loadErrorMessageView()
            }
        }
    }
    

    whenever your WebView fails to load page it calls onReceivedError callback there you can show error layout. For error view you can create error layout within your layout with initial visiblity View.GONE and make it visible when error occurrs.

    Changes to your XML file

    <WebView 
       android:id="@+id/webView"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/> 
    
    <LinearLayout
       android:id="@+id/error_screen"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
    
      <Textview 
        android:id="@+id/error_msg" />
      ................
      <ImageView
        android:id=:"@+id/error_icon/>
      //error view
    
    
    </LinearLayout>
    

    In loadErrorMessageView you can do this

    loadErrorMessageView() {
     webview.setVisibility(View.GONE);
     error_screen.setVisibility(View.VISIBLE);
     error_msg.setText("Some error Occurred");
    }
    

    Similarly you can do for NoInternet case maybe you can show "No internet message" than "Some error occurred" I hope this clears your doubt

    0 讨论(0)
  • 2021-01-06 18:18

    You can add loadUrl to call custom page in asset folder. Change the page name of your name page.

    inner class Callback : WebViewClient() {
            override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
                Toast.makeText(applicationContext, "No Internet Access!", Toast.LENGTH_SHORT).show()
                view.loadUrl("file:///android_asset/nameofyourpage.html")
             }
    }
    
    0 讨论(0)
提交回复
热议问题