文字显示效果自己脑补:头疼,产品提了个需求,要求富文本展示,欧克好了!过了几天又要求实现打字机效果
一、我的实现:
/**
* 普通文本实现打字机效果
*
* // In an Activity: myTextView.typeWrite(this, "Hello, world!", 33L)
* // In a Fragment: myTextView.typeWrite(viewLifecycleOwner, "Hello, world!", 33L)
*/
fun TextView.typeWrite(lifecycleOwner: LifecycleOwner, text: String, intervalMs: Long) {
this@typeWrite.text = ""
lifecycleOwner.lifecycleScope.launch {
repeat(text.length) {
delay(intervalMs)
this@typeWrite.text = text.take(it + 1)
}
}
}
/**
* 复文本实现打字机效果
*
* // In an Activity: myTextView.typeWrite(this, "Hello, world!", 33L)
* // In a Fragment: myTextView.typeWrite(viewLifecycleOwner, "Hello, world!", 33L)
*/
fun TextView.typeWrite(lifecycleOwner: LifecycleOwner, text: Spanned, intervalMs: Long) {
this@typeWrite.text = ""
lifecycleOwner.lifecycleScope.launch {
repeat(text.length) {
delay(intervalMs)
this@typeWrite.text = text.take(it + 1)
}
}
}
二、我的思路和理解
既然是富文本展示,实现:HtmlCompat.fromHtml( "......", HtmlCompat.FROM_HTML_MODE_LEGACY )
纯文本的打字机效果简单,不就是循环打印即可,随后我看了fromHtml()的方法源码,


原来富文本最终的转换只是一个字符数组,通过子类Spanned实现富文本显示
安卓实现富文本展示我知道有两种: 加载前端html代码或者通过SpannableString
本文介绍了如何使用Kotlin和协程在Android中实现文本打字机效果。首先,作者提到了产品的需求,即在富文本展示中加入打字机效果。接着,他详细阐述了自己的实现方法,指出对于纯文本,可以通过循环打印实现,而对于富文本,他研究了源码,理解到富文本最终是转化为字符数组进行显示。文章还提及了Android中富文本展示的两种方式,并推荐了相关资源进行深入学习。

3736

被折叠的 条评论
为什么被折叠?



