ข้อดีอย่างหนึ่งของแท็บที่กำหนดเองคือสามารถผสานรวมเข้ากับแอปได้อย่างราบรื่น ในส่วนนี้ของคู่มือแท็บที่กำหนดเอง คุณจะได้เรียนรู้วิธีเปลี่ยนลักษณะที่ปรากฏและลักษณะการทำงานของแท็บที่กำหนดเองให้ตรงกับแอปของคุณ
ตั้งค่าสีของแถบเครื่องมือ
ก่อนอื่น ให้ปรับแต่งแถบที่อยู่ของแท็บที่กำหนดเองให้สอดคล้องกับธีมของแอป ข้อมูลโค้ดด้านล่างจะเปลี่ยนสีแถบเครื่องมือเริ่มต้นโดยเรียกใช้ 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()
การปรับแต่งเพิ่มเติม: ชื่อ, แถบแอปที่ซ่อนอัตโนมัติ และไอคอนปิดที่กำหนดเอง
คุณสามารถดำเนินการเพิ่มเติมอีก 2-3 อย่างเพื่อปรับ UI ของแท็บที่กำหนดเองให้ตรงกับความต้องการของคุณ
- ซ่อนแถบ URL เมื่อเลื่อนเพื่อเพิ่มพื้นที่ให้ผู้ใช้สำรวจเนื้อหาเว็บโดยใช้
setUrlBarHidingEnabled()(true) - แสดงชื่อเอกสารแทน URL ผ่าน
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()
การตั้งค่า URL ที่มาที่กำหนดเอง
คุณตั้งค่าแอปเป็น URL ที่มาได้เมื่อเปิด Custom Tab วิธีนี้จะช่วยให้เว็บไซต์ทราบว่าการเข้าชมมาจากที่ใด
val customTabsIntent = CustomTabsIntent.Builder().build()
customTabsIntent.intent.putExtra(
Intent.EXTRA_REFERRER,
Uri.parse("android-app://${context.packageName}")
)