我想在android中使用webview加載一個url。這是我的WebView看起來像如何在android中加載webview時繼續/忽略錯誤?
public class WebViewFragment extends Fragment {
private static final String LOG_TAG = WebViewFragment.class.getName();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_view_fragment, container, false);
init(rootView);
return rootView;
}
private void init(View rootView) {
Bundle bundle = getArguments();
ImageView backButtonIV = (ImageView) rootView.findViewById(R.id.backButtonImage);
backButtonIV.setOnClickListener(new PopBackStackClickListener(getActivity()));
String title = bundle.getString(BundleConstants.WEB_HEADER_TEXT);
TextView headerTextTV = (TextView) rootView.findViewById(R.id.pageTitle);
headerTextTV.setText(title);
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setWebViewClient(new MyWebView());
String urlToLoad = bundle.getString(BundleConstants.WEB_URL);
Log.d(LOG_TAG, "Opening url :" + urlToLoad);
webView.loadUrl(urlToLoad);
}
private class MyWebView extends WebViewClient {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return super.shouldInterceptRequest(view, request);
}
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return true;
}
}
}
我把onReceivedHttpEror一個斷點,發現有兩個「未找到」的錯誤。基本上有兩個.png文件沒有找到。 webview出於這個原因停止加載頁面。我怎樣才能忽略這些錯誤並繼續?因爲在android之外,如果我嘗試打開鏈接,則網頁加載正常,並且錯誤僅記錄在控制檯中。但它不妨礙頁面的加載。我如何在android webview中實現相同的功能併成功加載頁面?
我刪除調用超。它沒有工作。它仍然沒有加載頁面。 – Karu
嘗試重寫shouldInterceptRequest並返回null而不是調用super也 – DKIT