由自定义视图中的懒惰Kotlin

目前,在自定义视图中使用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