如何在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) ,而不必在每个构造函数中明确地调用它。

使用默认参数的构造函数:

 class CustomComponent @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : FrameLayout(context, attrs, defStyle) { fun init { // Initialize your view } } 

@JvmOverloads注释告诉Kotlin生成三个重载的构造函数,所以它们也可以在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块中的用法。