WebView中加載頁面錯(cuò)誤處理

github地址(完整Demo下載避归,歡迎訪問)

https://github.com/zhouxu88/ErroWebViewDemo

在Android項(xiàng)目中昵慌,我們通常會(huì)用WebView來加載網(wǎng)頁面,當(dāng)我們的手機(jī)沒有聯(lián)網(wǎng)涧衙,或是服務(wù)端不小心癱瘓的時(shí)候哪工,WebView展示的效果就比較丑奥此。

Paste_Image.png

解決辦法

我們自定義一個(gè)View用來展示加載失敗的樣子,或者我們也可以直接寫一個(gè)錯(cuò)誤展示的HTML讓W(xué)ebView加載等等雁比。我們進(jìn)行重寫的方法是WebViewClient的onReceivedError()方法稚虎。

效果圖

自定義加載網(wǎng)頁錯(cuò)誤的view.jpg

MainActivity:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private WebView webView;
    private FrameLayout loadingLayout; //提示用戶正在加載數(shù)據(jù)
    private RelativeLayout webParentView;
    private View mErrorView; //加載錯(cuò)誤的視圖

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

        webView = (WebView) findViewById(R.id.webView);
        loadingLayout = (FrameLayout) findViewById(R.id.loading_layout);
        initErrorPage();//初始化自定義頁面
        initWebView();
    }

    private void initWebView() {
        //加載需要顯示的網(wǎng)頁
        webView.loadUrl("http://www.baidu.com/");
        WebSettings mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);    //允許加載javascript
        mWebSettings.setSupportZoom(true);          //允許縮放
        mWebSettings.setBuiltInZoomControls(true);  //原網(wǎng)頁基礎(chǔ)上縮放
        mWebSettings.setUseWideViewPort(true);      //任意比例縮放
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //6.0以下執(zhí)行
                Log.i(TAG, "onReceivedError: ------->errorCode" + errorCode + ":" + description);
                //網(wǎng)絡(luò)未連接
                showErrorPage();
            }

            //處理網(wǎng)頁加載失敗時(shí)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                //6.0以上執(zhí)行
                Log.i(TAG, "onReceivedError: ");
                showErrorPage();//顯示錯(cuò)誤頁面
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.i(TAG, "onProgressChanged:----------->" + newProgress);
                if (newProgress == 100) {
                    loadingLayout.setVisibility(View.GONE);
                }
            }

         
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                Log.i(TAG, "onReceivedTitle:title ------>" + title);
                if (title.contains("404")){
                    showErrorPage();
                }
            }
        });

        webParentView = (RelativeLayout) webView.getParent(); //獲取父容器
    }

    /**
     * 顯示自定義錯(cuò)誤提示頁面,用一個(gè)View覆蓋在WebView
     */
    private void showErrorPage() {
        webParentView.removeAllViews(); //移除加載網(wǎng)頁錯(cuò)誤時(shí)偎捎,默認(rèn)的提示信息
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        webParentView.addView(mErrorView, 0, layoutParams); //添加自定義的錯(cuò)誤提示的View
    }

    /***
     * 顯示加載失敗時(shí)自定義的網(wǎng)頁
     */
    private void initErrorPage() {
        if (mErrorView == null) {
            mErrorView = View.inflate(this, R.layout.layout_load_error, null);
        }
    }
}
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.zx.errowebviewdemo.MainActivity">

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


   <!--加載提示的loading圖-->
   <include
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       layout="@layout/loading_anim"
       android:layout_centerInParent="true"/>
</RelativeLayout>
  • layout_load_error.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/load_error_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--加載網(wǎng)頁錯(cuò)誤的提示圖-->
    <ImageView
        android:id="@+id/error_iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:contentDescription="@null"
        android:src="@mipmap/no_data" />

    <!--點(diǎn)擊提示文字蠢终,重新加載網(wǎng)頁-->
    <TextView
        android:id="@+id/reload_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/error_iv"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="8dp"
        android:gravity="center"
        android:text="數(shù)據(jù)獲取失敗\n,  請(qǐng)檢查網(wǎng)絡(luò)后再重試 ~~~" />
</RelativeLayout>
  • layout/loading_anim.xml
<?xml version="1.0" encoding="utf-8"?><!--加載提示圖-->

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/loading_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@null"
            android:scaleType="centerCrop"
            android:src="@drawable/beijing" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:contentDescription="@null"
            android:scaleType="centerCrop"
            android:src="@drawable/loading_anim" />

        <!--loading提示圖-->
        <TextView
            android:id="@+id/loading_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_horizontal"
            android:layout_marginBottom="3dp"
            android:gravity="center"
            android:text="@string/please_wait"
            android:textColor="#ffffff" />

    </FrameLayout>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市茴她,隨后出現(xiàn)的幾起案子寻拂,更是在濱河造成了極大的恐慌,老刑警劉巖丈牢,帶你破解...
    沈念sama閱讀 217,084評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祭钉,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡己沛,警方通過查閱死者的電腦和手機(jī)慌核,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泛粹,“玉大人遂铡,你說我怎么就攤上這事【фⅲ” “怎么了扒接?”我有些...
    開封第一講書人閱讀 163,450評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)们衙。 經(jīng)常有香客問我钾怔,道長(zhǎng),這世上最難降的妖魔是什么蒙挑? 我笑而不...
    開封第一講書人閱讀 58,322評(píng)論 1 293
  • 正文 為了忘掉前任宗侦,我火速辦了婚禮,結(jié)果婚禮上忆蚀,老公的妹妹穿的比我還像新娘矾利。我一直安慰自己,他們只是感情好馋袜,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評(píng)論 6 390
  • 文/花漫 我一把揭開白布男旗。 她就那樣靜靜地躺著,像睡著了一般欣鳖。 火紅的嫁衣襯著肌膚如雪察皇。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,274評(píng)論 1 300
  • 那天泽台,我揣著相機(jī)與錄音什荣,去河邊找鬼矾缓。 笑死,一個(gè)胖子當(dāng)著我的面吹牛稻爬,可吹牛的內(nèi)容都是我干的嗜闻。 我是一名探鬼主播,決...
    沈念sama閱讀 40,126評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼因篇,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼泞辐!你這毒婦竟也來了笔横?” 一聲冷哼從身側(cè)響起竞滓,我...
    開封第一講書人閱讀 38,980評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎吹缔,沒想到半個(gè)月后商佑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,414評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡厢塘,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評(píng)論 3 334
  • 正文 我和宋清朗相戀三年茶没,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片晚碾。...
    茶點(diǎn)故事閱讀 39,773評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡抓半,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出格嘁,到底是詐尸還是另有隱情笛求,我是刑警寧澤,帶...
    沈念sama閱讀 35,470評(píng)論 5 344
  • 正文 年R本政府宣布糕簿,位于F島的核電站探入,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏懂诗。R本人自食惡果不足惜蜂嗽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望殃恒。 院中可真熱鬧植旧,春花似錦、人聲如沸离唐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽侯繁。三九已至胖喳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間贮竟,已是汗流浹背丽焊。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工较剃, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人技健。 一個(gè)月前我還...
    沈念sama閱讀 47,865評(píng)論 2 370
  • 正文 我出身青樓写穴,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親雌贱。 傳聞我的和親對(duì)象是個(gè)殘疾皇子啊送,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容