自定义标签页的一个优势是,它们可以无缝集成到您的应用中。在自定义标签页指南的这一部分中,您将了解如何更改自定义标签页的外观和行为,使其与您的应用保持一致。
设置工具栏的颜色
首先,自定义自定义标签页的地址栏,使其与应用的主题保持一致。以下代码段通过调用 setDefaultColorSchemeParams() 更改了默认工具栏颜色。如果您的应用还支持深色配色方案,请通过 .setColorSchemeParams(CustomTabsIntent.COLOR_SCHEME_DARK, …) 进行设置。
// get the current toolbar background color (this might work differently in your app)
@ColorInt val colorPrimaryLight = ContextCompat.getColor(
this@MainActivity,
R.color.md_theme_light_primary
)
@ColorInt val colorPrimaryDark = ContextCompat.getColor(
this@MainActivity,
R.color.md_theme_dark_primary
)
val intent = CustomTabsIntent.Builder()
// set the default color scheme
.setDefaultColorSchemeParams(
CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorPrimaryLight)
.build()
)
// set the alternative dark color scheme
.setColorSchemeParams(
CustomTabsIntent.COLOR_SCHEME_DARK,
CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorPrimaryDark)
.build()
)
.build()
工具栏现在具有自定义背景和前景颜色。
配置自定义进入和退出动画
接下来,您可以使用 setStartAnimation 和 setExitAnimation 定义自定义启动和退出动画,从而让应用中的自定义标签页启动(和退出)体验更加顺畅:
val intent = CustomTabsIntent.Builder()
// …
.setStartAnimations(
this@MainActivity,
R.anim.slide_in_right,
R.anim.slide_out_left
)
.setExitAnimations(
this@MainActivity,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
)
.build()
进一步自定义:标题、自动隐藏应用栏和自定义关闭图标
您还可以执行其他一些操作,根据需要调整自定义标签页的界面。
- 在滚动时隐藏网址栏,以便用户有更多空间使用
setUrlBarHidingEnabled()(true)探索 Web 内容。 - 通过
setShowTitle()(true)显示文档标题,而不是网址。 - 自定义关闭按钮,使其与应用中的用户体验流程相匹配,例如,显示返回箭头,而不是默认的
X图标:setCloseButtonIcon()(myCustomCloseIcon)。
这些都是可选的,但可以改善应用中的自定义标签页体验。
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.graphics.drawable.toBitmap
// …
val myCustomCloseIcon = AppCompatResources
.getDrawable(this, R.drawable.ic_baseline_arrow_back_24)
?.toBitmap()
val intent = CustomTabsIntent.Builder()
// …
.setUrlBarHidingEnabled(true)
.setShowTitle(true)
.apply { myCustomCloseIcon?.let { setCloseButtonIcon(it) } }
.build()
设置自定义引荐来源网址
您可以在启动自定义标签页时将应用设置为引荐来源。这样,您就可以让网站知道其流量来自何处。
val customTabsIntent = CustomTabsIntent.Builder().build()
customTabsIntent.intent.putExtra(
Intent.EXTRA_REFERRER,
Uri.parse("android-app://${context.packageName}")
)
接下来:了解如何向自定义标签页添加自定义操作。