I am trying to view an HTML content in my Compose HTML View using AndroidView.. I use this library to load images asynchronously using Coil.
1) My HTML text with tag i want to load
"<p>some dummy text.</p><p>some dummy text.</p><p>some dummy text.</p>
<br><img src=\"https://example.com/PublishingImages/333.png\" alt=\"\"
style=\"margin:5px;\" /><br><br></p>"
2) My HTMLView
fun HtmlText(
modifier: Modifier = Modifier,
html: String,
textStyle: TextStyle = contentStyle,
okHttpClient: OkHttpClient = koinInject()
) {
AndroidView(
modifier = modifier,
update = {
it.text = fromHtml(
it.context,
okHttpClient,
html
)
},
factory = { context ->
TextView(context).apply {
textSize = textStyle.fontSize.value
}
}
)
}
3) fromHtml method
fun fromHtml(
context: Context,
okHttpClient: OkHttpClient,
html: String
): Spannable = parse(context, okHttpClient, html, sourceModifier).apply {
removeLinksUnderline()
styleBold(context)
}
private fun parse(
context: Context,
okHttpClient: OkHttpClient,
html: String
): Spannable = HtmlCompat.fromHtml(
html,
HtmlCompat.FROM_HTML_MODE_COMPACT,
ImageGetter(context, okHttpClient, sourceModifier),
null
) as Spannable
4) ImageGetter
class ImageGetter(
val context: Context,
okHttpClient: OkHttpClient
) : Html.ImageGetter {
private fun getLoader(): ImageLoader {
return ImageLoader.Builder(context)
.okHttpClient(okHttpClient)
.respectCacheHeaders(false)
.logger(DebugLogger())
.build()
}
override fun getDrawable(source: String?): Drawable {
val drawablePlaceholder = DrawablePlaceHolder(context)
getLoader().enqueue(
ImageRequest.Builder(context)
.data(finalSource)
.networkCachePolicy(CachePolicy.ENABLED)
.diskCachePolicy(CachePolicy.ENABLED)
.memoryCachePolicy(CachePolicy.DISABLED)
.target { drawable ->
drawablePlaceholder.updateDrawable(drawable)
}
.build(),
)
// Since this loads async, we return a "blank" drawable, which we update later
return drawablePlaceholder
}
}
My Observations
- Image loads from server (or from cache) correctly.
- However, the TextView doesn't get updated after the image is loaded.
- I think since the image drawablePlaceholder is empty at start, the TextView starts with no text. But after the image is retrieved, it is not updated.
How can I fix this issue??