前言
经常写自定义View的同学都会知道,当View发生改变时,想要主动的去刷新View,无外乎两个方法:主线程调用invalidate(),子线程调用postInvalidate()。调用上述两个方法后,系统会在合适的时候去刷新我们的View,即回调onDraw方法。带着这样的认知,我们默认会认为在排除其他干扰因素的情况时,只要不调用invaidate()系列方法,我们的自定义View只会保持上一次刷新时的样子。可是Android就总是会给我们带来惊喜(ㄒoㄒ),接下来的测试将会刷新你的认知。
开始
我们先来创建两个自定义View:
/**
* 自定义View
*/
class MyView : View {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
private var mColor: Int = Color.BLUE
private var mPaint: Paint = Paint()
private var mTextPaint: Paint = Paint()
init {
mPaint.color = mColor
mPaint.strokeWidth = 10f
mPaint.style = Paint.Style.STROKE
mTextPaint.color = Color.BLACK
mTextPaint.textSize = 50f
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
Log.e("MyView", "onDraw")
canvas?.drawRect(100f, 100f, 300f, 300f, mPaint)
canvas?.drawText("MyView", 50f, 50f, mTextPaint)
}
open fun setColor(@ColorInt color: Int) {
this.mColor = color
mPaint.color = mColor
}
}
/**
* 自定义View使用双缓冲刷新
*/
class MyViewUseBitmap : View {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context<

在Android开发中,自定义View的刷新通常通过invalidate()或postInvalidate()触发。然而,测试发现,一个使用双缓冲的自定义View在未调用刷新方法时也会自动更新,而另一个没有使用双缓冲的View则按预期工作。这种行为可能在某些情况下导致不可控的刷新。通过调整代码,可以确保View仅在调用invalidate()时刷新,从而解决问题。
最低0.47元/天 解锁文章
9025

被折叠的 条评论
为什么被折叠?



