2017-05-27 37 views
3

我有一個自定義佈局如下如何在init函數中訪問不是成員變量的構造函數參數?

class CustomComponent : FrameLayout { 

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

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { 
     initAttrs(attrs) 
    } 

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { 
     initAttrs(attrs) 
    } 

    init { 
     LayoutInflater.from(context).inflate(R.layout.view_custom_component, this, true) 
    } 

    fun initAttrs(attrs: AttributeSet?) { 
     val typedArray = context.obtainStyledAttributes(attrs, R.styleable.custom_component_attributes, 0, 0) 
     my_title.text = resources.getText(typedArray 
       .getResourceId(R.styleable.custom_component_attributes_custom_component_title, R.string.component_one)) 
     typedArray.recycle() 
    } 
} 

現在,每一個構造函數,我必須顯式調用initAttrs(attrs),因爲我無法找到辦法在我init函數來訪問attrs

有沒有一種方法,我可以在init功能訪問attrs,所以我可以打電話從initinitAttrs(attrs),而不必顯式調用它在每一個構造函數?

+0

如果不是所有的構造函數都有'attrs'參數,你認爲這可以工作嗎? – yole

+0

當它沒有提供時,理想情況下,我們應該跳過調用'initAttr'。您提出了一個很好的問題,因爲當所有構造函數中都沒有'attrs'時,我認爲這是不可能的。但是我想要問一下在那裏的Kotlin專家,鑑於讀'attrs'在構建自定義佈局方面非常常見,並且在java中,有一些很好的處理方法,而不需要複製'initAttr'的調用的地方。 – Elye

+0

你可以使用'lateinit var attrs:AttributeSet?'並在每個構造函數中設置值,然後在initAttrs()中使用它() – Debu

回答

4

使用構造函數的默認參數:

class CustomComponent @JvmOverloads constructor(
    context: Context, 
    attrs: AttributeSet? = null, 
    defStyle: Int = 0 
) : FrameLayout(context, attrs, defStyle) { 

    fun init { 
     // Initialize your view 
    } 
} 

@JvmOverloads註解告訴科特林產生三個重載的構造函數,使他們能夠在Java中被稱爲好。

在你init功能,attrs變得可作爲可空類型:

fun init { 
    LayoutInflater.from(context).inflate(R.layout.view_custom_component, this, true) 

    attrs?.let { 
     val typedArray = context.obtainStyledAttributes(it, R.styleable.custom_component_attributes, 0, 0) 
     my_title.text = resources.getText(typedArray 
       .getResourceId(R.styleable.custom_component_attributes_custom_component_title, R.string.component_one)) 
     typedArray.recycle() 
    } 
} 

itlet塊的使用。

+0

優秀的答案! – Elye

相關問題