【问题标题】:how can i decode HTML code to Android by kotlin?如何通过 kotlin 将 HTML 代码解码为 Android?
【发布时间】:2018-09-09 04:36:01
【问题描述】:

我正在尝试解码 HTML 实体,目前我的代码是:

val str = name
val textView = findViewById<View>(R.id.text) as TextView
textView.text = Html.fromHtml(str, Html.FROM_HTML_MODE_COMPACT)

这里的错误信息是:

kotlin.TypeCastException: null cannot be cast to non-null type android.widget.TextView

【问题讨论】:

    标签: android casting kotlin


    【解决方案1】:

    您的错误与 HTML 处理无关,您在这一行遇到异常,因为 findViewById 正在返回 null,然后转换为 TextView 失败:

    val textView = findViewById<View>(R.id.text) as TextView
    

    没有上下文很难判断为什么会发生这种情况,但问题是没有找到 ID 为 text 的视图。

    • 如果您在 Activity 中,请确保您在致电 setContentView 后执行此操作。
    • 如果您在Fragment 中,请确保在onCreateView 方法运行后执行此操作。
    • 无论哪种情况,请确保您实际使用的布局包含 ID 为 @+id/textTextView

    此外,您首先将TextView 查找为View,然后再进行转换,您可以执行以下任一操作:

    val textView = findViewById<TextView>(R.id.text)
    val textView: TextView = findViewById(R.id.text)
    

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 2019-11-19
      • 2018-06-24
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多