【发布时间】:2021-03-10 23:00:33
【问题描述】:
我正在尝试扩展 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)
【问题讨论】:
-
在大多数情况下,当子类化视图时,您只需要创建两个参数的构造函数并使用两个参数调用超构造函数。视图在 XML 布局中工作不需要其他重载。
-
@Tenfour04 你的意思是,如果我只使用 XML 布局进行膨胀,我只需要担心 context 和 attributeSet 参数吗?
-
是的............
-
如果您想支持默认样式/属性并允许人们指定其他默认样式/属性,则只需实现三参数和四参数构造函数。如果您只需要从 XML 进行简单的膨胀,那么您只需要两个参数的构造函数。
标签: android android-layout kotlin