我正在使用 webview 在android studio中创建一个应用,我想要这样的东西。 “如果该网址无法加载并显示屏幕截图之类的内容,则我的应用将显示一个吐司,提示不正确的网址。”如果网址正确加载,则吐司将显示正确的网址。
我该怎么做。
MainActivity.Java
public class MainActivity extends AppCompatActivity {
WebView mWebv;
ProgressBar spinner;
private String main_url = "http://my.wifi/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.webview_spinner);
mWebv = findViewById(R.id.web_view);
WebSettings settings = mWebv.getSettings();
settings.setJavaScriptEnabled(true);
mWebv.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
spinner.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
spinner.setVisibility(View.GONE);
}
});
mWebv.getSettings().setJavaScriptEnabled(true);
mWebv.loadUrl(main_url);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebv.canGoBack()) {
mWebv.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
答案 0 :(得分:1)
只需将此方法重写到您的setWebViewClient中即可
mWebv.setWebViewClient(new WebViewClient(){
...
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// do some stuff
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView inView, WebResourceRequest inReq,WebResourceError inError)
{
// do some stuff
onReceivedError(inView, inError.getErrorCode(), inError.getDescription().toString(), inReq.getUrl().toString());
}
});
感谢@ newton_cr7提出修改建议