像Gmail应用程序一样处理android WebView中的外部链接

时间:2017-03-14 07:19:58

标签: android webview

我是网络开发人员。我目前正在使用WebView在Android Studio上开发Android应用程序,它将我的网站作为Android应用程序访问。我的一个网页包含许多外部链接。我的目标是使Android应用程序可以处理像Gmail应用程序那样的外部链接(也像facebook和Line do)。 以下是gmail app的示例。

An email contains external link

Link clicked, then application open a new activity acts like a browser without leaving Gmail application

知道怎么做吗?

1 个答案:

答案 0 :(得分:11)

这很简单。您必须按照Gergely的建议使用Chrome Custom Tabs以及评论。以下是可帮助您实现此目的的小功能代码。

首先将此依赖项添加到build.gradle(Module:app)

compile 'com.android.support:customtabs:23.4.0'

第二步将以下函数添加到您的代码中,并简单地将字符串URL传递给它。

private void redirectUsingCustomTab(String url)
{
    Uri uri = Uri.parse(url);

    CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();

    // set desired toolbar colors
    intentBuilder.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary));
    intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));

    // add start and exit animations if you want(optional)
    /*intentBuilder.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    intentBuilder.setExitAnimations(this, android.R.anim.slide_in_left,
            android.R.anim.slide_out_right);*/

    CustomTabsIntent customTabsIntent = intentBuilder.build();

    customTabsIntent.launchUrl(activity, uri);
}

休息它会照顾自己。由于Chrome自定义标签可以自定义,因此您可以将菜单添加到工具栏中。有关详细信息,您可以访问Google自己的官方文档here

希望它能帮助你开始:)