首页 > 解决方案 > 使用 Kotlin 扩展 java 类首选项时的多个构造函数

问题描述

我正在尝试采用这个 Time Preference java 类并将其转换为 Kotlin:

public TimePreference(Context context) {
    this(context, null);
}
public TimePreference(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}
public TimePreference(Context context, AttributeSet attrs,
        int defStyleAttr) {
    this(context, attrs, defStyleAttr, defStyleAttr);
}
public TimePreference(Context context, AttributeSet attrs,
        int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);

    // Do custom stuff here
    // ...
    // read attributes etc.
}

我能够获得主构造函数,但不能获得辅助构造函数。由于运行时布局膨胀错误,我遇到了崩溃。

class SpinnerPreference constructor(context: Context, attrs:  
AttributeSet, defStyleAttributes: Int, defStyleRes: Int) : 
Preference(context, attrs, defStyleAttributes, defStyleRes) {

}

标签: javaandroidkotlin

解决方案


这次从 commonsware 的评论中再次仔细检查了文档,这似乎有效:)。

class SpinnerPreference : Preference {

constructor(context: Context, attrs: AttributeSet, defStyleAttributes: Int, defStyleRes: Int) : super(context, attrs, defStyleAttributes, defStyleRes)
constructor(context: Context, attrs: AttributeSet, defStyleAttributes: Int) : super(context, attrs, defStyleAttributes)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context) : super(context)

}

推荐阅读