简体   繁体   English

Android Kotlin-如何扩展ConstraintLayout?

[英]Android Kotlin - How to extend ConstraintLayout?

I'd like my ConstaintLayout to carry extra additional properties, but I have trouble extending it. 我希望ConstaintLayout带有额外的其他属性,但是我很难扩展它。 More precisely I have trouble putting correct constructor into 更准确地说,我在将正确的构造函数放入时遇到了麻烦

class myCL(): ConstraintLayout(???) {
}

To make sure you don't get any quirks in behavior, you should implement it like this. 为了确保您在行为上没有任何怪异,您应该像这样实现它。

class myCL: ConstraintLayout {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?,
                @AttrRes defStyleAttr: Int) : super(context, attrs, defStyleAttr)
}

The constructor you really need is the one with all arguments: 您真正需要的构造函数是带有所有参数的构造函数:

class myCL(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) :
    ConstraintLayout(context, attrs, defStyleAttr) {
}

if you want to implement all three constructors without much hassle you can use @JvmOverloads and use sensible defaults. 如果要轻松实现所有三个构造函数,则可以使用@JvmOverloads并使用明智的默认值。

class myCL @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ConstraintLayout(context, attrs, defStyleAttr) {
}

see https://developer.android.com/reference/android/support/constraint/ConstraintLayout 参见https://developer.android.com/reference/android/support/constraint/ConstraintLayout

You can also do something like this to restict to only one super call -- 您也可以这样做,只打一个super电话-

class MyConstraintLayout: ConstraintLayout {

   constructor(context: Context) : this(context, null)
   constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, -1)
   constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : super(context, attrs, defStyleAttr)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM