【问题标题】:WebView: Stop from opening links in browser and keep in appWebView:停止在浏览器中打开链接并保留在应用程序中
【发布时间】:2015-03-13 01:23:33
【问题描述】:

所以我对 Java 很陌生,我在我的 android 应用程序中使用 webview 来显示我的响应式网站页面。我意识到我应该开发一个专门的应用程序,但我还没有那么好。

话虽如此,当有人使用我网站中的链接时,它会尝试在他们的手机上打开一个浏览器窗口,而我宁愿将其保留在应用程序中。这是我当前的 webview 配置。我尝试了一些我在这里阅读过的解决方案,但它们似乎都不起作用(可能是由于我的知识有限)。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String url ="http://dirtywasted.com/";
        WebView view=(WebView) this.findViewById(R.id.webView);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl(url);
    }

我应该添加什么来保持在应用内点击链接?

【问题讨论】:

标签: java android webview


【解决方案1】:

您可以将 WebClient 设置为 webview 并覆盖 shouldOverrideUrlLoading,例如:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String url ="http://dirtywasted.com/";
    WebView view=(WebView) this.findViewById(R.id.webView);
    view.getSettings().setJavaScriptEnabled(true);
    view.setWebViewClient(new WebViewClient() {
            @Override
            public bool shouldOverrideUrlLoading(WebView view, String url) {
                //url will be the url that you click in your webview.
                //you can open it with your own webview or do
                //whatever you want

                //Here is the example that you open it your own webview.
                view.loadUrl(url);
                return true;
            }       
         });
    view.loadUrl(url);
}

【讨论】:

  • 其实你不需要覆盖shouldOverrideUrlLoading,只需设置一个WebViewClient就可以了:view.setWebViewClient(new WebViewClient())
  • 但是如果你想处理带有其他行为的url,例如在其他activity中打开它,你应该重写这个方法来获取url。
猜你喜欢
  • 1970-01-01
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 2014-07-12
  • 2018-02-11
  • 2014-03-12
相关资源
最近更新 更多