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
,所以我可以打電話從init
initAttrs(attrs)
,而不必顯式調用它在每一個構造函數?
如果不是所有的構造函數都有'attrs'參數,你認爲這可以工作嗎? – yole
當它沒有提供時,理想情況下,我們應該跳過調用'initAttr'。您提出了一個很好的問題,因爲當所有構造函數中都沒有'attrs'時,我認爲這是不可能的。但是我想要問一下在那裏的Kotlin專家,鑑於讀'attrs'在構建自定義佈局方面非常常見,並且在java中,有一些很好的處理方法,而不需要複製'initAttr'的調用的地方。 – Elye
你可以使用'lateinit var attrs:AttributeSet?'並在每個構造函數中設置值,然後在initAttrs()中使用它() – Debu