Kotlin父子类初始化顺序

Out*_*ash 0 java android android-view kotlin

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

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

子类(科特林):

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

超类(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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*zzi 6

这很正常。初始化顺序是

  1. 家长班
  2. 儿童班

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

open class Parent {
  init { print("parent ") } 
}

class Child : Parent() {
  init { print("child ") } 
}

fun main(args: Array<String>) {
  Child() 
}
Run Code Online (Sandbox Code Playgroud)

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