«

Android使用webview时出现404如何替换掉原来的错误页面

时间:2024-3-2 19:38     作者:韩俊     分类: Android


import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.Dialog;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.KeyEvent;

import android.view.Menu;

import android.view.View;

import android.webkit.WebSettings;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import android.widget.ImageView;



public class MainActivity extends Activity {





private WebView webView;

private ImageView img;

String url = "http://sttuolian.wicp.net:8086";

private Dialog myDialog;











@SuppressLint("SetJavaScriptEnabled")

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activitymain);



webView = (WebView) findViewById(R.id.eshetong_wv);

img = (ImageView) findViewById(R.id.wordpress_logo);



WebSettings webSettings = webView.getSettings();

// 支持JS

webSettings.setJavaScriptEnabled(true);

// 将图片调整到适合webView的大小

webSettings.setUseWideViewPort(false);

// webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

// 支持缩放

webSettings.setSupportZoom(true);

webSettings.setBuiltInZoomControls(true);

// 可以访问文件

webSettings.setAllowFileAccess(true);

// 支持通过JS打开新窗口

webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

// 支持自动加载图片

webSettings.setLoadsImagesAutomatically(true);

// 使滚动条不占位

webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);



webView.setWebViewClient(new WebViewClient() {



@Override

public void onReceivedError(WebView view, int errorCode,

String description, String failingUrl) {



view.stopLoading();

view.clearView();

Message msg = handler.obtainMessage();// 发送通知,加入线程

msg.what = 1;// 通知加载自定义404页面

handler.sendMessage(msg);// 通知发送!

}



@Override

public boolean shouldOverrideUrlLoading(WebView view, String url) {

return false;

// return super.shouldOverrideUrlLoading(view, url);

}



@Override

public void onPageFinished(WebView view, String url)

{

super.onPageFinished(view, url);

}

});



webView.loadUrl(url);





}



@Override

public boolean onCreateOptionsMenu(Menu menu) {

// TODO Auto-generated method stub

getMenuInflater().inflate(R.menu.main, menu);

return true;

}



@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {



// TODO Auto-generated method stub

if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {

webView.goBack(); // goBack()表示返回WebView的上一页面

return true;

}

return super.onKeyDown(keyCode, event);

}



protected Handler handler = new Handler() {

public void handleMessage(Message message) {

if(message.what==1){

webView.stopLoading();

//载入本地assets文件夹下面的错误提示页面404.html

webView.loadUrl("file:///android_asset/404.html");

}else{

myDialog.show();

}

}

};

}

        <p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>

标签: android

热门推荐