簡體   English   中英

如何在 Kotlin 中擴展 ConstraintLayout

[英]How to extend ConstraintLayout in Kotlin

我正在嘗試擴展 ConstraintLayout 以與 Kotlin 中的復合組件一起使用。 我發現的大多數示例都與此類似,其中構造函數有 3 個參數。 但是,還有第四個構造函數,它采用另一個參數 defStyleRes。 使用它的正確默認值是什么? 基於此,我認為 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用於第三個和第四個 arguments,但在我看來,您最好只公開一個雙參數構造函數並調用超類自己的雙參數構造函數。


當從 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實例的樣式。 有關更多信息,請參閱 此文檔(搜索“使用默認樣式主題屬性”)。
  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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM