这可能是一个迟到的帖子,但它可能会帮助其他开发人员......
您需要在 webview 上设置 setWebViewClient,然后在其上加载 URL,如下所示,
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
上面代码的一些背景,文档用文字描述了 shouldOverrideUrlLoading 方法。
* @param view The WebView that is initiating the callback.
* @param request Object containing the details of the request.
* @return {@code true} if the host application wants to leave the current WebView
* and handle the url itself, otherwise return {@code false}.
*/
@Override
@SuppressWarnings("deprecation") // for invoking the old shouldOverrideUrlLoading.
@RequiresApi(21)
public boolean shouldOverrideUrlLoading(@NonNull WebView view,
@NonNull WebResourceRequest request) {
if (Build.VERSION.SDK_INT < 21) return false;
return shouldOverrideUrlLoading(view, request.getUrl().toString());
}
如果您看到上面关于返回值的文档,它会说,
@return {@code true} if the host application wants to leave the current WebView
*and handle the url itself, otherwise return {@code false}.
所以它简单地说,如果你从 shouldOverrideUrlLoading 方法返回 true,它会要求你设备的默认浏览器处理打开 URL 的请求,如果您返回 false,那么您的 URL 将仅通过 webview 加载。
现在您可以在此 setWebViewClient 调用之后在 webview 中加载您的 URL,也可以在返回值之前在 shouldOverrideUrlLoading 方法中加载您的 URL。