简体   繁体   English

如何在 Android 的 WebView 的外部浏览器和应用程序内打开链接

[英]How to open links both in an external browser and in-app within a WebView for Android

I'm trying to create both links to open internally within the my app's WebView and others which open externally within whichever default browser.我正在尝试创建两个链接以在我的应用程序的 WebView 和其他在任何默认浏览器中从外部打开的链接内部打开。 I have seen previous questions and answers regarding but none seem to be working and I think the solutions may be outdated?我已经看到了以前的问题和答案,但似乎没有一个有效,我认为解决方案可能已经过时了?

Any suggestions of how best to achieve this would be appreciated.任何关于如何最好地实现这一目标的建议将不胜感激。 Opening links within the app is working fine, it's just getting links to open in an external browser where applicable.在应用程序中打开链接工作正常,它只是让链接在适用的外部浏览器中打开。 Maybe some kind of class or url parameter check?也许某种 class 或 url 参数检查? I haven't managed to get either to work so far.到目前为止,我还没有设法让任何一个工作。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        myWebView.loadUrl("https://website.com/");
        myWebView.setWebViewClient(new WebViewClient());
    }

    @Override
    public void onBackPressed() {
        if (myWebView.canGoBack()) {
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

You can do it like this你可以这样做

webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(wantToOpenExternal){
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    String title = "Select a browser";
                    Intent chooser = Intent.createChooser(intent, title);
                    startActivity(chooser);
                    return true;//cancel the current load
                }
                return false;//continue the current load
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM