我有一个自定义布局如下
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()
}
}
Run Code Online (Sandbox Code Playgroud)
现在对于每个构造函数,我必须显式调用,initAttrs(attrs)因为我找不到attrs在我的init函数中访问的方法.
有没有一种方法,我可以访问attrs的init功能,这样我就可以打电话initAttrs(attrs),从init而无需显式调用它在每一个构造函数的?
使用具有默认参数的构造函数:
class CustomComponent @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle) {
fun init {
// Initialize your view
}
}
Run Code Online (Sandbox Code Playgroud)
该@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()
}
}
Run Code Online (Sandbox Code Playgroud)
需要注意的使用it中let块.
| 归档时间: |
|
| 查看次数: |
1694 次 |
| 最近记录: |