目前,在自定义视图中使用by Lazy
会破坏其在Android Studio中的可视化效果。无法使用isEditMode
,因为它仅在方法内可用,而不在可变初始化范围内。只有解决方法是使用lateinit和/或Delegates.notNull()。
有没有解决方法呢?
示例:
class ImageViewCircleBg : ImageView {
private var circleBgColor = R.color.colorPrimary
private val paint by lazy {
Paint().apply {
style = Paint.Style.FILL
isAntiAlias = true
}
}
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
val ta = context.theme.obtainStyledAttributes(attrs, R.styleable.ImageViewCircleBg, 0, 0)
circleBgColor = ta.getColor(R.styleable.ImageViewCircleBg_roundBgColor, circleBgColor)
ta.recycle()
this.paint.color = circleBgColor
}
在android studio设计窗口中产生以下错误:
The following classes could not be instantiated:
- ....ImageViewCircleBg (Open Class, Show Exception, Clear Cache)
Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE Exception Details java.lang.IncompatibleClassChangeError: Found class kotlin.Lazy, but interface was expected at ...ImageViewCircleBg.getPaint(ImageViewCircleBg.kt:-1)
用懒惰代替:
private val paint: Paint
init {
paint = Paint().apply {
style = Paint.Style.FILL
isAntiAlias = true
}
}
解决问题。
错误:
java.lang.IncompatibleClassChangeError: Found class kotlin.lazy, but interface was expected