SpannableStringBuilder 不显示来自 Firebase (Kotlin) 的每个数据的图像跨度

SpannableStringBuilder not display image span for every data from Firebase (Kotlin)

我从 FireBase 检索数据并尝试在每个数据旁边显示图像 (TextView)。但是图像只显示在第一个数据上。

这是输出:

我希望每个数据都有图像。

这是我的代码:

val database = FirebaseDatabase.getInstance().reference

val getData = object : ValueEventListener {
     override fun onDataChange(snapshot: DataSnapshot) {
     
          val myData = SpannableStringBuilder()

          for (i in snapshot.children) {
               val data = i.child("myData").value

               myData.append("$data\n\n")
               
               // Get image from drawable and set size
               val drawable: Drawable? = context?.let { ContextCompat.getDrawable(it, R.drawable.myImage) }
               drawable?.setBounds(0, 0, textView.lineHeight, textView.lineHeight)
               
               // Set image span to the first letter
               val span: ImageSpan? = drawable?.let { ImageSpan(it, ImageSpan.ALIGN_BASELINE) }
               myData.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
          }

          textView.text = myData
     }

     override fun onCancelled(error: DatabaseError) {

     }
}

database.addValueEventListener(getData)

问题出在 myData.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)。 您始终将图像跨度设置在整个字符串的第一个。做这样的事情:

override fun onDataChange(snapshot: DataSnapshot) {

    val builder = SpannableStringBuilder()

    snapshot.children.forEach { data ->
        builder.append("$data#") // the `#` doesn't mind and will be replaced with the image span

        val span = context?.let {
            ImageSpan(it, R.drawable.myImage, DynamicDrawableSpan.ALIGN_BASELINE)
        }

        builder.setSpan(
            span,
            builder.length - 1,
            builder.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        builder.append("\n\n") // at the end, append new lines
    }
    
    textView.text = builder
}