自定义界面

自定义标签页的一个优势是,它们可以无缝集成到您的应用中。在本自定义标签页指南的此部分,您将了解如何更改自定义标签页的外观和行为,使其与您的应用相匹配。

设置工具栏的颜色

采用自定义浅色配色方案的自定义标签页
浅色模式
采用自定义深色配色方案的自定义标签页
深色模式

首先,自定义自定义标签页的地址栏,使其与应用的主题保持一致。以下代码段通过调用 setDefaultColorSchemeParams() 更改了默认的工具栏颜色。如果您的应用还支持深色配色方案,请通过 .setColorSchemeParams(CustomTabsIntent.COLOR_SCHEME_DARK, …) 进行设置。

// get the current toolbar background color (this might work differently in your app) @ColorInt int colorPrimaryLight = ContextCompat.getColor(MainActivity.this, R.color.md_theme_light_primary); @ColorInt int colorPrimaryDark = ContextCompat.getColor(MainActivity.this, R.color.md_theme_dark_primary);  CustomTabsIntent intent = new CustomTabsIntent.Builder()         // set the default color scheme         .setDefaultColorSchemeParams(new CustomTabColorSchemeParams.Builder()                 .setToolbarColor(colorPrimaryLight)                 .build())         // set the alternative dark color scheme         .setColorSchemeParams(CustomTabsIntent.COLOR_SCHEME_DARK, new CustomTabColorSchemeParams.Builder()                 .setToolbarColor(colorPrimaryDark)                 .build())         .build(); 

工具栏现在具有自定义背景和前景颜色。

配置自定义进入和退出动画

接下来,您可以使用 setStartAnimationsetExitAnimation 定义自定义启动和退出动画,让应用中启动(和离开)自定义标签页的体验更加顺畅:

CustomTabsIntent intent = new CustomTabsIntent.Builder()  .setStartAnimations(MainActivity.this, R.anim.slide_in_right, R.anim.slide_out_left) .setExitAnimations(MainActivity.this, android.R.anim.slide_in_left, android.R.anim.slide_out_right) .build(); 

进一步的自定义:标题、自动隐藏的 AppBar 和自定义关闭图标

您还可以执行一些操作,根据自己的需求调整自定义标签页的界面。

  • 滚动时隐藏网址栏,为用户提供更多空间来使用 setUrlBarHidingEnabled()(true) 探索网页内容。
  • 通过 setShowTitle()(true) 显示文档标题,而不是网址。
  • 自定义关闭按钮,使其与应用中的用户体验流程相匹配(例如,显示返回箭头而非默认的 X 图标):setCloseButtonIcon()(myCustomCloseIcon)

这些都是可选项,但它们可以改进应用中的自定义标签页体验。

Bitmap myCustomCloseIcon = getDrawable(R.drawable.ic_baseline_arrow_back_24)); CustomTabsIntent intent = new CustomTabsIntent.Builder()      .setUrlBarHidingEnabled(true)   .setShowTitle(true)   .setCloseButtonIcon(toBitmap(myCustomCloseIcon))   .build(); 

设置自定义引荐来源

您可以在启动自定义标签页时将自己的应用设置为引荐来源。这样,您就可以让网站知道其流量来自何处。

CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build() customTabsIntent.intent.putExtra(Intent.EXTRA_REFERRER,        Uri.parse("android-app://" + context.getPackageName())); 

后续:了解如何向自定义标签页添加自定义操作