自訂分頁的優點之一,就是能完美整合至應用程式。在本節的自訂分頁指南中,您將瞭解如何變更自訂分頁的外觀和行為,使其與應用程式相符。
設定工具列顏色
首先,自訂自訂分頁的網址列,使其與應用程式的主題一致。以下程式碼片段會呼叫 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()
進一步自訂:標題、自動隱藏 AppBar 和自訂關閉圖示
您還可以採取其他措施,根據需求調整自訂分頁的 UI。
- 使用
setUrlBarHidingEnabled()(true),在捲動時隱藏網址列,讓使用者有更多空間瀏覽網路內容。 - 透過
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}")
)
接下來,請瞭解如何為自訂分頁新增自訂動作。