我正在尝试扩展 ConstraintLayout 以与 Kotlin 中的复合组件一起使用。我找到的大多数例子都是 similar to this one ,其中构造函数有 3 个参数。然而,有一个fourth constructor它需要另一个参数 defStyleRes。正确使用的默认值是多少? Based on this我认为 0 有效,类似于 defStyleAttr。 我认为最终的代码应该是这样的:
class ClockButton @JvmOverloads constructor(
context: Context,
private val attributeSet: AttributeSet? = null,
private val defStyleAttr: Int = 0,
private val defStyleRes: Int = 0) : ConstraintLayout(context, attributeSet, defStyleAttr, defStyleRes)
最佳答案
tl;dr:您可以使用0
作为第三个和第四个参数,但在我看来,您最好只暴露一个双参数构造函数并调用父类(super class)自己的双参数构造函数。
当从 XML 扩充 View 时,仅调用两个参数的构造函数。因此,只有从 Java/Kotlin 代码中调用一参数、三参数和四参数构造函数才相关。
例如,如果您查看 MaterialButton
的源代码,您会发现它的双参数构造函数如下所示:
public MaterialButton(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.materialButtonStyle);
}
并且它有一个相应的三参数构造函数:
public MaterialButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
// approx. 30 lines omitted
}
它根本没有指定四参数构造函数。
以这种方式设置的好处有两个部分。
- 您可以通过在主题中指定
materialButtonStyle
属性来设置应用中所有MaterialButton
实例的样式。请参阅this documentation了解更多(搜索“使用默认样式主题属性”)。 - future 的开发人员可以对
MaterialButton
进行子类化,并在其双参数构造函数中指定不同的默认样式属性:
public class MySpecialButton extends MaterialButton {
public MySpecialButton(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs, R.attr.mySpecialStyle);
}
// ...
}
如果您不关心这些默认样式/属性,则可以完全忽略三参数和四参数构造函数,而只需调用父级的双参数构造函数:
class MyCompoundView(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs)
关于android - 如何在 Kotlin 中扩展 ConstraintLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66574115/