หากตัวจับคู่ที่ให้มาไม่เพียงพอสำหรับ Use Case ของคุณ คุณสามารถสร้างตัวจับคู่ของคุณเองได้โดยขยายคลาส DeepLinkMatcher
เมื่อขยาย DeepLinkMatcher<T, R> คุณต้องระบุอาร์กิวเมนต์ประเภท 2 รายการ ได้แก่ ประเภทคีย์การนำทางปลายทาง (T : Any) และประเภทผลลัพธ์การจับคู่ (R : DeepLinkMatcher.MatchResult<T>) หาก Matcher ไม่ต้องการการจัดอันดับผลลัพธ์ที่กำหนดเองหรือข้อมูลเมตาเพิ่มเติม ให้ใช้ DeepLinkMatcher.MatchResult<T> เป็นอาร์กิวเมนต์ประเภทที่ 2
ตัวอย่างเช่น ต่อไปนี้เป็นการใช้งานพื้นฐานของ TelDeepLinkMatcher ที่รองรับ URI tel (เช่น tel:5550100) เนื่องจาก URI tel เป็นแบบทึบแสง UriDeepLinkMatcher จึงไม่รองรับ
class TelDeepLinkMatcher : DeepLinkMatcher<DialerKey, DeepLinkMatcher.MatchResult<DialerKey>>() { override fun matchRequest(request: DeepLinkRequest): MatchResult<DialerKey>? { val uri = request.uri ?: return null if (uri.scheme != "tel") return null // Note: schemeSpecificPart is only available on Android val phoneNumber = uri.schemeSpecificPart ?: return null return MatchResult(DialerKey(phoneNumber = phoneNumber)) } }
จัดอันดับคลาส MatchResult ที่กำหนดเอง
หากมีวิธีที่มีความหมายในการเปรียบเทียบผลลัพธ์การจับคู่จาก Matcher ที่กำหนดเอง คุณควรขยาย DeepLinkMatcher.MatchResult และลบล้างเมธอด compareTo เพื่อจัดอันดับผลลัพธ์
เมื่อสร้างคลาสย่อย MatchResult ที่กำหนดเอง ให้อัปเดตการประกาศคลาสของ Matcher เพื่อระบุคลาสย่อยนั้นเป็นพารามิเตอร์ประเภทที่ 2 R (เช่น class TelDeepLinkMatcher : DeepLinkMatcher<DialerKey, TelMatchResult>()) ซึ่งจะช่วยให้ผู้เรียกเข้าถึงพร็อพเพอร์ตี้ผลลัพธ์ที่กำหนดเองได้โดยไม่ต้องดาวน์แคสต์ที่ไม่ได้เลือก
เช่น หากต้องการรองรับการจับคู่รูปแบบไวลด์การ์ดใน TelDeepLinkMatcher คุณสามารถใช้ TelMatchResult เพื่อให้มั่นใจว่าการทำงานแบบตรงทั้งหมดมีอันดับสูงกว่าการจับคู่ไวลด์การ์ด หากตัวจับคู่อยู่ใน withBackStack ให้แกะ WrappedMatchResult ออกก่อนเปรียบเทียบเพื่อให้ระบบประเมินลำดับความสำคัญเทียบกับผลลัพธ์การจับคู่ที่เกี่ยวข้อง ดังนี้
class TelMatchResult( key: DialerKey, val isExactMatch: Boolean, val patternLength: Int ) : DeepLinkMatcher.MatchResult<DialerKey>(key) { override fun compareTo(other: DeepLinkMatcher.MatchResult<DialerKey>): Int { // Unwrap if the other result is wrapped in a BackStackMatchResult or custom WrappedMatchResult val target = if (other is WrappedMatchResult<*>) other.matchResult else other if (target !is TelMatchResult) { // Determine precedence relative to other MatchResult types (e.g. UriMatchResult) return 1 } // An exact match wins over a wildcard/prefix match if (isExactMatch && !target.isExactMatch) return 1 if (!isExactMatch && target.isExactMatch) return -1 // The more specific (longer) pattern wins (e.g., tel:1800* versus tel:*) val lengthDiff = this.patternLength - target.patternLength if (lengthDiff != 0) { return lengthDiff } return 0 } }