Kotlin父子类的初始化顺序

时间:2019-02-01 15:22:35

标签: java android kotlin android-view

我有一个视图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)
        }
    }
}

SuperClass(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();
  }
}

1 个答案:

答案 0 :(得分: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的初始化,该类本身就会被初始化。