我正在使用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);
}
最佳答案
只需将此方法覆盖到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的编辑建议
关于java - 使用WebView检查URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54589312/