Jetpack Compose ช่วยให้การโต้ตอบใน Text มีความละเอียดสูง ตอนนี้การเลือกข้อความมีความยืดหยุ่นมากขึ้นและทำได้ในเลย์เอาต์ที่ประกอบกันได้ การโต้ตอบของผู้ใช้ในข้อความแตกต่างจากเลย์เอาต์ Composable อื่นๆ เนื่องจากคุณไม่สามารถเพิ่มตัวแก้ไขลงในส่วนของ Composable Text ได้ หน้านี้จะไฮไลต์ API ที่เปิดใช้การโต้ตอบของผู้ใช้
เลือกข้อความ
โดยค่าเริ่มต้น คอมโพสิเบิลจะเลือกไม่ได้ ซึ่งหมายความว่าผู้ใช้ไม่สามารถเลือกและคัดลอกข้อความจากแอปของคุณได้ หากต้องการเปิดใช้การเลือกข้อความ ให้รวมองค์ประกอบข้อความไว้ในคอมโพสิเบิล SelectionContainer ดังนี้
@Composable fun SelectableText() { SelectionContainer { Text("This text is selectable") } }
คุณอาจต้องการปิดใช้การเลือกในบางส่วนของพื้นที่ที่เลือกได้ โดยคุณต้องรวมส่วนที่เลือกไม่ได้ไว้ใน Composable DisableSelection ดังนี้
@Composable fun PartiallySelectableText() { SelectionContainer { Column { Text("This text is selectable") Text("This one too") Text("This one as well") DisableSelection { Text("But not this one") Text("Neither this one") } Text("But again, you can select this one") Text("And this one too") } } }
สร้างส่วนของข้อความที่คลิกได้ด้วย LinkAnnotation
หากต้องการฟังการคลิก Text คุณสามารถเพิ่มตัวแก้ไข clickable ได้ อย่างไรก็ตาม คุณอาจต้องการแนบข้อมูลเพิ่มเติมกับบางส่วนของค่า Text เช่น URL ที่แนบกับคำบางคำเพื่อเปิดในเบราว์เซอร์ ในกรณีเช่นนี้ คุณต้องใช้ LinkAnnotation ซึ่งเป็นคำอธิบายประกอบที่แสดงส่วนที่คลิกได้ของข้อความ
LinkAnnotation ช่วยให้คุณแนบ URL กับส่วนหนึ่งของ Text Composable ที่จะเปิดโดยอัตโนมัติเมื่อคลิกได้ ดังที่แสดงในข้อมูลโค้ดต่อไปนี้
@Composable fun AnnotatedStringWithLinkSample() { // Display multiple links in the text Text( buildAnnotatedString { append("Go to the ") withLink( LinkAnnotation.Url( "https://developer.android.com/", TextLinkStyles(style = SpanStyle(color = Color.Blue)) ) ) { append("Android Developers ") } append("website, and check out the") withLink( LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles(style = SpanStyle(color = Color.Green)) ) ) { append("Compose guidance") } append(".") } ) }
นอกจากนี้ คุณยังกำหนดค่าการกระทำที่กำหนดเองเพื่อตอบสนองต่อการคลิกของผู้ใช้ในส่วนของ Composable Text ได้ด้วย ในข้อมูลโค้ดต่อไปนี้ เมื่อผู้ใช้คลิก "Jetpack Compose" ระบบจะแสดงลิงก์และบันทึกเมตริกหากผู้ใช้คลิกลิงก์
@Composable fun AnnotatedStringWithListenerSample() { // Display a link in the text and log metrics whenever user clicks on it. In that case we handle // the link using openUri method of the LocalUriHandler val uriHandler = LocalUriHandler.current Text( buildAnnotatedString { append("Build better apps faster with ") val link = LinkAnnotation.Url( "https://developer.android.com/jetpack/compose", TextLinkStyles(SpanStyle(color = Color.Blue)) ) { val url = (it as LinkAnnotation.Url).url // log some metrics uriHandler.openUri(url) } withLink(link) { append("Jetpack Compose") } } ) }
แนะนำสำหรับคุณ
- หมายเหตุ: ข้อความลิงก์จะแสดงเมื่อ JavaScript ปิดอยู่
- ความหมายใน Compose
- การช่วยเหลือพิเศษใน Compose
- Material Design 2 ใน Compose