2017-05-22 50 views
3

比方說,我有相同的構造如何在不同的類中共享相同的構造函數,即在接口中定義構造函數?

class Button: AppCompatButton { 

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { 
    } 

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { 
    } 

    constructor(context: Context) : super(context) { 
    } 
    //Some custom implementation 
    //............ 
} 

class TextView: AppCompatTextView { 

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { 
    } 

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { 
    } 

    constructor(context: Context) : super(context) { 
    } 
    //Some custom implementation 
    //............ 
} 

所以我需要一些接口或基類,它讓我繼承像TextView的,按鈕的EditText等

形式的多個視圖中的Android多個自定義視圖喜歡的東西

abstract class BaseView<T : View> : T { 
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { 
    } 

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { 
    } 

    constructor(context: Context) : super(context) { 
    } 
} 

或者

interface ViewConstructor { 
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { 
    } 

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { 
    } 

    constructor(context: Context) : super(context) { 
    } 
} 

所以我只使用一個接口或基類,不要複製過去的承包商。如何在Kotlin中實現這樣的目標?

P.S.請不要建議使用基類作爲View並使用基類創建派生視圖。我使用XML,我需要EditText,Button和其他視圖。

回答

0

這是極不可能的,你會找到解決你的問題。首先,構造函數不是按照你的建議繼承的。它們的存在是爲了初始化你的繼承鏈的一部分,所以任何從你繼承的任何人都仍然需要轉發給超類的構造函數。我相當肯定你被卡在每個View類中重新聲明這些視圖構造函數(儘管其中一些可能會基於你的實例化用例而放棄)。

4

作爲解決其編寫許多構造函數,你可以使用默認參數與@JvmOverloads相結合,輕鬆搞定所有4層View構造,而只寫一個主構造你的類:

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

} 
相關問題