【问题标题】:Hiding view default constructors隐藏视图默认构造函数
【发布时间】:2016-07-18 15:41:08
【问题描述】:

在 Kotlin 中有没有办法隐藏(放置在其他地方)视图的默认构造函数?也许创建一个子视图或扩展或类似的东西。

目前我所有的观点都是这样的,有点啰嗦:

class MyView(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int): View(context, attrs, defStyleAttr, defStyleRes) {
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): this(context, attrs, defStyleAttr, 0)
    constructor(context: Context, attrs: AttributeSet?): this(context, attrs, 0, 0)
    constructor(context: Context): this(context, null, 0)
}

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    你可以使用default arguments:

    class MyView(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0): View(context, attrs, defStyleAttr, defStyleRes)
    

    如果您需要从 Java 调用这些构造函数,请考虑 applying 构造函数的 @JvmOverloads 注释:

    class MyView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0): View(context, attrs, defStyleAttr, defStyleRes)
    

    【讨论】:

    • 不知道我是怎么忘记的。谢谢!
    • 您能否更新您的答案:class MyView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0): View(context, attrs ,defStyleAttr,defStyleRes)?当使用来自 xml 的视图时,它的工作原理。
    • 格式有点奇怪。我认为这是将构造函数拆分为多行的好案例
    • @voddan 此语法与在类中包含构造函数不同。这仍然允许您在类中使用 init{}
    • @Heinrisch 看我的回答
    【解决方案2】:

    @udalov 答案的格式或多或少是正确的:

    class MyView(context: Context, 
                 attrs: AttributeSet? = null, 
                 defStyleAttr: Int = 0, 
                 defStyleRes: Int = 0) : View(context, attrs, defStyleAttr, defStyleRes)
    

    class MyView @JvmOverloads constructor(
            context: Context, 
            attrs: AttributeSet? = null, 
            defStyleAttr: Int = 0, 
            defStyleRes: Int = 0
    ) : View(context, attrs, defStyleAttr, defStyleRes) {
        // ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 1970-01-01
      • 2010-11-28
      • 2016-07-23
      相关资源
      最近更新 更多