【问题标题】:class extends AppCompatImageView Supertype initialization is impossible without primary constructor没有主构造函数,类扩展 AppCompatImageView 超类型初始化是不可能的
【发布时间】:2021-07-09 05:31:45
【问题描述】:

有一个扩展 AppCompatImageView 的自定义 Imageview 类

显示错误:没有主构造函数就无法初始化超类型

class ImageViewVasl : AppCompatImageView() {
    constructor(context: Context) : super(context) {
        initialize(context = context, attrs = null)
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initialize(context = context, attrs = attrs)
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initialize(context = context, attrs = attrs)
    }
    private fun initialize(
        context: Context?,
        attrs: AttributeSet?
    ) {

    }
}

【问题讨论】:

    标签: android kotlin android-custom-view


    【解决方案1】:

    尝试:

    class ImageViewVasl() : AppCompatImageView(){
      constructor(context: Context) : this(context) {
            initialize(context = context, attrs = null)
        }
      ...
    }
    

    或:

    class ImageViewVasl: AppCompatImageView{
        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) {
            ...
        }
    }
    

    【讨论】:

    • 委托调用链中存在循环
    【解决方案2】:

    你需要调用父类的构造函数:

    class PieChart(context: Context, attrs: AttributeSet) : View(context, attrs)
    

    在您的源代码中,我看不到您在哪里调用父级的构造函数。 此链接中的更多详细信息:https://developer.android.com/training/custom-views/create-view

    【讨论】:

    • 期待“this”或“super”构造函数调用
    • 我在你的源代码中看到,你有三个构造方法。其中一个应该使用“super”,另外两个使用“this”。阅读此博客:antonioleiva.com/custom-views-android-kotlin
    • 已解决 : class ImageViewVasl(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : AppCompatImageView( context, attrs, defStyleAttr ){}
    【解决方案3】:

    只要去掉()后:AppCompatImageView(),像这样

    class ImageViewVasl : AppCompatImageView {
    ...
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      相关资源
      最近更新 更多