跳到主要内容

文本

⚠️ 已弃用:推荐使用数据绑定(Data Binding)替代直接操作文本运行(Text Run)。

文本运行(Text Runs)是 Rive 中用于显示动态文本的元素。

通过 RiveAnimationView 读取文本

使用 RiveAnimationView 上的 .getTextRunValue() API 读取文本运行的值:

fun getTextRunValue(textRunName: String): String?

提供文本运行名称,将返回 Rive 文本运行的值;如果无法查询文本运行,返回 null

通过 RiveAnimationView 设置文本

使用 RiveAnimationView 上的 .setTextRunValue() API 设置文本运行的值:

fun setTextRunValue(textRunName: String, textValue: String)

提供文本运行名称和 textValue 字符串参数来设置新的文本值。

如果提供的 textRunName 无法在活动画板上查询到 Rive 文本运行,Rive 将抛出 RiveException,你可能需要在应用中捕获并妥善处理。

引用 Rive TextRun

也可以查询活动画板获取 Rive 文本运行引用,然后手动获取/设置文本属性。

private val textRun by lazy(LazyThreadSafetyMode.NONE) {
yourRiveAnimationView.artboardRenderer?.activeArtboard?.textRun("name")
}

示例

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import app.rive.runtime.kotlin.RiveAnimationView

class DynamicTextActivity : AppCompatActivity(), TextWatcher {
private val animationView by lazy(LazyThreadSafetyMode.NONE) {
findViewById<RiveAnimationView>(R.id.dynamic_text)
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dynamic_text)
val editText = findViewById<EditText>(R.id.text_run_value)
editText.addTextChangedListener(this)
}

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
animationView.getTextRunValue("name")
}

override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
animationView.setTextRunValue("name", s.toString())
}
}

嵌套画板中的文本

通过 RiveAnimationView 读取文本

使用路径参数访问嵌套画板中的文本运行:

fun getTextRunValue(textRunName: String, path: String): String?

通过 RiveAnimationView 设置文本

fun setTextRunValue(textRunName: String, textValue: String, path: String)

引用嵌套 Rive TextRun

private val textRun by lazy(LazyThreadSafetyMode.NONE) {
yourRiveAnimationView.artboardRenderer?.activeArtboard?.textRun("name", "path/to/artboard")
}