【问题标题】:Kotlin parent and child class initialization orderKotlin 父子类初始化顺序
【发布时间】:2019-02-01 15:22:34
【问题描述】:

我有一个视图SubEpoxyRecyclerView,它是我的父类EpoxyRecyclerView 的子类。当这个视图被初始化时,超类EpoxyRecyclerView在构造函数体中调用方法setItemSpacingPx(Int)

当这个方法被调用时,我的类变量都没有被初始化!应用程序在itemDecorator.pxBetweenItems 线上崩溃,说明itemDecorator 为空,这是不可能的

子类(Kotlin):

class SubEpoxyRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : EpoxyRecyclerView(context, attrs, defStyleAttr) {

    private val itemDecorator: Decor = Decor()
    private val someInt: Int = 5
    private var someBoolean: Boolean = true

    override fun setItemSpacingPx(spacingPx: Int) {
        // Called from superclass. Debug: itemDecorator is null, 
        // someInt is 0, someBoolean is false

        removeItemDecoration(itemDecorator)
        itemDecorator.pxBetweenItems = spacingPx

        if (spacingPx > 0) {
            addItemDecoration(itemDecorator)
        }
    }
}

超类(Java - 库):

public class EpoxyRecyclerView extends RecyclerView {
  public EpoxyRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    if (attrs != null) {
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EpoxyRecyclerView,
          defStyleAttr, 0);
      setItemSpacingPx(a.getDimensionPixelSize(R.styleable.EpoxyRecyclerView_itemSpacing, 0));
      a.recycle();
    }

    init();
  }
}

【问题讨论】:

    标签: java android kotlin android-view


    【解决方案1】:

    这很正常。初始化顺序为

    1. 父类
    2. 儿童班

    查看此示例以了解您的代码不工作的原因:

    open class Parent {
      init { print("parent ") } 
    }
    
    class Child : Parent() {
      init { print("child ") } 
    }
    
    fun main(args: Array<String>) {
      Child() 
    }
    

    根据上面的例子,main方法首先打印“parent”,然后打印“child”。在您的情况下,SubEpoxyRecyclerView 类的变量未初始化,因为一旦 EpoxyRecyclerView 的初始化完成,该类本身就会被初始化。

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 2020-02-12
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多