2023年12月30日 星期六

【Android】 在 Compose 中使用 Views : 使用 Compose 尚未提供的 UI 元素


例子

@Composable
private fun PlantDescriptionHTML(description: String) {
    // Remembers the HTML formatted description. Re-executes on a new description
    // remember HTML 格式的描述。在有變動時根據新的描述重新執行
    val htmlDescription = remember(description) {
        HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_COMPACT)
    }

    // Displays the TextView on the screen and updates with the HTML description when inflated
    // Updates to htmlDescription will make AndroidView recompose and update the text
    // 在螢幕上顯示 TextView 並在膨脹時更新 HTML 描述
    // 更新 htmlDescription 將使 AndroidView 重新組合並更新文本
    AndroidView(
        factory = { context ->
            TextView(context).apply {
                movementMethod = LinkMovementMethod.getInstance()
            }
        },
        update = {
            it.text = htmlDescription
        }
    )
}

@Preview(showBackground = true, widthDp = 320)
@Composable
private fun PlantDescriptionHTMLPreview() {
    MaterialTheme {
        PlantDescriptionHTML("測試<br>test 換了一行")
    }
}




參考資料


0 comments:

張貼留言