不要导航到WebView中的其他页面,禁用链接和引用

Dan*_*ion 21 html android webview

我在Android中有一个webView,我在其中打开一个html网页.但它充满了链接和图像,当我点击其中一个时,它会加载到我的webview中.我想禁用此行为,因此如果我单击链接,请不要加载它.我已经尝试过这个解决方案并为myselft编辑了一下,但没有奏效.我的webview客户端代码:

private boolean loaded = false;

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

    if(loaded == false){
        view.loadUrl(url);
        loaded = true;
        return true;
    }else{
        return false;
    }

}
Run Code Online (Sandbox Code Playgroud)

我的webview实现和设置.

WebView wv = (WebView) findViewById(R.id.recipeWv);
    ourWebViewClient webViewClient = new ourWebViewClient();
    webViewClient.shouldOverrideUrlLoading(wv, URLsave);
    wv.setWebViewClient(webViewClient);
    wv.setFocusableInTouchMode(false);
    wv.setFocusable(false);
    wv.setClickable(false);
    WebSettings settings = wv.getSettings();
    settings.setDefaultTextEncodingName("utf-8");

    settings.setLoadWithOverviewMode(true);
    settings.setBuiltInZoomControls(true);
Run Code Online (Sandbox Code Playgroud)

示例:如果用户在我的webview中打开StackOverflow主页并单击其中一个链接(如"问题"),则webview应保留在StackOverflow主页上.

Sle*_*kra 24

您应该在类变量中保存当前的url并检查它是否与加载的url相同.当用户点击链接时,shouldOverrideUrlLoading会调用该网站并检查网站.像这样的东西:

private String currentUrl;

public ourWebViewClient(String currentUrl) {
    this.currentUrl = currentUrl;
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.equals(currentUrl)) {
        view.loadUrl(url);  
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

重要提示:不要忘记设置WebViewClient为您的WebView.

ourWebViewClient webViewClient = new ourWebViewClient(urlToLoad);
wv.setWebViewClient(webViewClient);
Run Code Online (Sandbox Code Playgroud)


Tar*_*run 14

实现WebViewClient并从WebView Client的此方法返回true

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)


Ami*_*pta 5

如果你想在不同的窗口中打开一个网页的内部链接,那么

不要使用

WebView webView;//Your WebView Object
webView.setWebViewClient(new HelpClient());// Comment this line
Run Code Online (Sandbox Code Playgroud)

B'coz setWebViewClient()方法负责在同一个 webview 中打开一个新页面。如此简单的注释这一行。

private class HelpClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("www.example.com")) {
            // This is my web site, so do not override; let my WebView load the page
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这会奏效。