การดึง content มาแสดงใน Chrome Custom Tab
ขออัพเดตบล็อกเป็น androidx และ kotlin เน้ออ~~
เราจะใช้เจ้า Chrome Custom Tab เพื่อมาอ่านบล็อกจากหน้าเว็บของเรากัน โดยกดที่ card item ใน blog list ของเรานั่นเอง

แต่ละแอปที่เราใช้กัน เช่น facebook google แม้กระทั่ง line เอง ก็ใช้ custom chrome tab ซึ่งมันโหลดหน้าเว็บไวมาก แถมยังใช้ feature จากใน chrome เช่น save password หรือการแชร์เว็บไปยังแอปอื่น



แหล่งข้อมูล
อันนี้มาตอนปี 2016 https://developer.chrome.com/multidevice/android/customtabs
จริงๆอ่านอันนี้ก็จบไวดี

ส่วนก่อนหน้านี้จะอ่านจาก
Exploring Chrome Customs Tabs on Android



เริ่ม implement ได้!
ก่อนอื่นเลย add dependencies ก่อนเลยจ้า
dependencies {
implementation 'androidx.browser:browser:1.0.0'
}
บอกก่อนเลยว่าไม่ต้องไปทำ layout UI ใดๆ แค่ implement code ก็ใช้ได้แล้วจ้า เลยมาเล่าว่าเรา implement อะไรบ้าง อาจจะแตกต่างกันไป และตอนนี้คิดว่าน่าจะมี url
กันอยู่แล้วเนอะ
ก่อนอื่นมาประกาศตัวแปรที่เป็น CustomTabsIntent
ขึ้นมา
val intentBuilder = CustomTabsIntent.Builder()
การเปิด custom tab ก็ไม่ยากเลย แค่นี้เลย
intentBuilder.build().launchUrl(context, Uri.parse(url))
ผลที่ได้จ้า

ต่อมาเรามา custom ต่างๆเพิ่มเพื่อความสวยงามมม
เราจะเปลี่ยนสี toolbar ด้านบนให้เป็น colorPrimary
intentBuilder.setToolbarColor(ContextCompat.getColor(context, R.color.colorPrimary))
และเราอยากให้มันโชว์ title ด้วยว่ากำลังอ่านบล็อกชื่ออะไรอยู่
intentBuilder.setShowTitle(true)
แล้วก็เปลี่ยนปุ่มปิดจาก x เป็น <- เพื่อย้อนกลับไปหน้า blog list
intentBuilder.setCloseButtonIcon(
BitmapFactory.decodeResource(
context.resources,
R.drawable.ic_action_arrow_left
)
)
ข้อควรระวัง drawable จะใช้เป็น 24dp เท่านั้น ไม่งั้นมันไม่ยอมเปลี่ยน icon ให้เรานะ

ผลก็จะออกมาสวยงามมม แต่พอกดปุ่มสามจุดบนขวาพบว่า ยังไม่มีปุ่มให้แชร์เลยนี่นา


ดังนั้นเพิ่ม memu share ในปุ่มสามจุดด้วยการใส่สิ่งนี้ลงไปจ้า
เราจะใส่ putExtra(Intent.EXTRA_REFERRER, Uri.parse("android-app://" + context.packageName))
เพื่อทำการ tracking ว่าเปิดจากในแอพนะ
ผลที่ได้ก็คืออออ


และเราสามารถใส่ animation เพิ่มได้ด้วยนะเออ แต่ R.anim.silde_in_right กับ R.anim.silde_out_left เราต้องใส่ resource เพิ่มเองนะ
intentBuilder.setStartAnimations(
context,
R.anim.slide_in_right,
R.anim.slide_out_left
)
intentBuilder.setExitAnimations(
context,
android.R.anim.slide_in_left,
android.R.anim.slide_out_right
)
ถ้าเราต้องการให้ chrome custom tab ของเราโหลดเร็วขึ้น ต้องใส่ warmup ไปด้วย แต่ใส่ลงไปเปล่าๆปลี้ๆไม่ได้ ต้องเปิด browser service ของ chrome custom tab ขึ้นมาก่อน แล้วใส่ลงไปข้างใน
ดังนั้น ผลที่ออกมา จะเป็นประมาณนี้
จบแล้ว ฝากร้านสิ รอไร
อย่าลืมกด like กด share บทความกันด้วยนะคะ :)
Posted by MikkiPastel on Sunday, 10 December 2017