android - 如何在 Kotlin 中扩展 ConstraintLayout

标签 android android-layout kotlin

我正在尝试扩展 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
}

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

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

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

相关文章:

android - kotlin 按数组列表中属性值的总和分组

Android:如何只适合系统窗口内的 map 对象?

Android如何在dp中指定 9-patch 角半径?

android - Textview 卡在布局底部

android - 仅当缓存时发生错误:通过改型实现缓存

android - Kotlin 注释格式在 Android Studio 中自动与上一行换行

java - 延迟初始化完整性检查 : Variable might not have been initialized

java - 数组/链表 : performance depends on the *direction* of traversal?

android - JobService() 如何停止自身?

android - Kotlin 中的错误(改造)预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT