Android:让Link始终保持在程序的WebView中跳转

本文介绍如何在Android应用中使用WebView加载特定网址,并通过重写shouldOverrideUrlLoading方法来控制不同链接的行为。对于指定的Host地址,链接将在WebView内打开;而对于其他链接,则会启动新的Activity进行处理。

在Android的WebView中,当点击调用网页的链接时,默认的动作是跳转到系统设定的默认浏览器中。如果想让链接始终在当前WebView中跳转的话,就需要添加以下代码:

1 WebView webView = (WebView) findViewById(R.id.webView1);
2 webView.setWebViewClient(new WebViewClient());

如果只是想让特定的URL保持在WebView中跳转的话,可以通过重写WebViewClient来实现,示例如下:

 1 private class MyWebViewClient extends WebViewClient {
 2     @Override
 3     public boolean shouldOverrideUrlLoading(WebView view, String url) {
 4         if (Uri.parse(url).getHost().equals("192.168.3.95")) {
 5             // This is my web site, so do not override; let my WebView load the page
 6             return false;
 7         }
 8         // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
 9         Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
10         startActivity(intent);
11         return true;
12     }
13 }

其中的192.168.3.95可以转换成任何想要保持在WebViewClient中跳转的Host名称,例如www.example.com。

最后别忘了把webView.setWebViewClient(new WebViewClient());改为webView.setWebViewClient(new MyWebViewClient());

转载于:https://www.cnblogs.com/ilovewindy/p/3745015.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值