如何在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() } }
注意it
在let
块中的用法。
- lateinit属性尚未初始化
- 在Anko异步调用(Kotlin)中捕获异常时出错
- 转换字节码时出错 – DexException – Firebase身份验证
- Android – ViewDataBinding.inflate不会膨胀嵌套的自定义视图
- 使用Kotlin和Firebase通过onAuthStateChanged回调触发sendEmailVerification
- 如果在构造函数中定义类属性,如何编写自定义getter?
- 从1.0.2 – 1.0.3升级Kotlin:java.lang.NoSuchMethodError:没有虚方法provideInjectedData $ app_compileDebugKotlin()
- 匕首2与Kotlin的多重绑定
- Kotlin和Android数据绑定(BuildTools 2.0.0)