在Android10手机上,当textview set text(spannable)有很多ReplacementSpans时,在view.onMeasure中需要花费大量的时间,所以发生了ANR。
我在三星G981N和G975N手机(安卓10)上进行了测试。
根据android profiler的数据,android.graphics.text.LineBreaker.nComputeLineBreaks运行了大部分的运行时间。
Here图像,并在我测试的代码下面。
(compileSdkVersion 29)
(使用ReplacementSpan将A*100替换为K*2 )
(textLength = 3000正常运行,但30000发生异常)
private fun test() {
val text = StringBuffer()
val textLength = 30000
val spanLength = 100
var count = 0
while (count < textLength) {
text.append("A")
count++
}
val spannable = text.toSpannable()
var index = 0
while (index < (textLength / spanLength)) {
val span = TestReplacementSpan()
spannable.setSpan(span, index * spanLength, index * spanLength + spanLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
index++
}
binding.textview.text = spannable
}
class TestReplacementSpan : ReplacementSpan() {
private val replaceText = "KK"
override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: FontMetricsInt?): Int {
if (fm != null) {
paint.getFontMetricsInt(fm)
}
return Math.round(paint.measureText(replaceText, 0, replaceText.length))
}
override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
canvas.drawText(replaceText, 0, replaceText.length, Math.max(x, 0f), y.toFloat(), paint)
}
}发布于 2020-03-25 19:44:06
添加下面的代码,问题就解决了
textview.breakStrategy = Layout.BREAK_STRATEGY_SIMPLEhttps://stackoverflow.com/questions/60813591
复制相似问题