【问题标题】:How to extend ConstraintLayout in Kotlin如何在 Kotlin 中扩展 ConstraintLayout
【发布时间】: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


【解决方案1】:

tl;dr:您可以0 用于第三个和第四个参数,但在我看来,您最好只公开一个双参数构造函数和调用超类自己的双参数构造函数。


当从 XML 扩展视图时,只会调用两个参数的构造函数。因此,只有在 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
}

它根本没有指定一个四参数的构造函数。

以这种方式设置的好处分为两部分。

  1. 您可以通过在主题中指定materialButtonStyle 属性来设置应用程序中所有MaterialButton 实例的样式。请参阅this documentation 了解更多信息(搜索“使用默认样式主题属性”)。
  2. 未来的开发者可以继承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)

【讨论】:

  • 这是一个很好的解释。感谢您花时间解释它
猜你喜欢
  • 2018-11-10
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多