How can I force a webview app to open links in it instead of open them in the default android browser depending on the domain?

醉酒当歌 提交于 2020-01-23 02:51:06

问题


I've just begun developing android apps, so I need some help with my webview app which is easy to understand. So, this is my specific question:

How can I force a webview app to open links in it instead of open them in the default browser depending on domain?

Please enclose an edited/expanded version of this code with your answer:

public class WebViewActivity extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("www.example.com");

The domain whose content I want to open in webview is, let's say: www.qwerty.com Every other link should be open by the default browser.

Many thanks in advance.


回答1:


You'll have to create a WebViewClient:

public class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

And then set it to your WebView like this:

webview.setWebViewClient(new MyWebViewClient());



回答2:


You have to evaluate the url passed in the custom WebViewClient. The boolean shouldOverrideUrlLoading has a true and a false value. When true, you send the url to the browser, when false, you stay in the WebView.

public class MyWebViewClient extends WebViewClient {
@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (Uri.parse(url).getHost().equals("www.qwerty.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;    
    }
}

Then from your Activity you call indeed the new WebClient

webview.setWebViewClient(new MyWebViewClient());


来源:https://stackoverflow.com/questions/14633367/how-can-i-force-a-webview-app-to-open-links-in-it-instead-of-open-them-in-the-de

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!