我在Kotlin中创建了一个自定义视图,并希望访问它的属性资源.
以下是我的代码
class CustomCardView : FrameLayout {
constructor(context: Context) : super(context)
constructor(context: Context,attrs: AttributeSet) : super(context,attrs)
constructor(context: Context,attrs: AttributeSet,defStyleAttr: Int) : super(context,attrs,defStyleAttr)
init {
LayoutInflater.from(context).inflate(R.layout.view_custom_card,this,true)
if (attrs != null) {
val a = context.obtainStyledAttributes(attrs,R.styleable.custom_card_view)
if (a.hasValue(R.styleable.custom_card_view_command)) {
var myString = a.getString(R.styleable.custom_card_view_command)
}
}
}
}
请注意,这将在init函数的attrs中出错.我想知道如何进入attrs?
解决方法
您无法从init块访问辅助构造函数参数.但至少有两种方法可以实现类似的功能.
第一种方法是使用具有默认参数的单个主构造函数而不是多个辅助构造函数.在这种情况下,您必须将@JvmOverloads注释应用于构造函数,以使Kotlin生成三个不同的构造函数.
class CustomCardView @JvmOverloads constructor(
context: Context,attrs: AttributeSet? = null,defStyleAttr: Int = 0
) : FrameLayout {
init {
LayoutInflater.from(context).inflate(R.layout.view_custom_card,true)
if (attrs != null) {
val a = context.obtainStyledAttributes(attrs,R.styleable.custom_card_view)
if (a.hasValue(R.styleable.custom_card_view_command)) {
var myString = a.getString(R.styleable.custom_card_view_command)
}
}
}
}
秒方法是两个链构造函数,并使用三个参数将init块内容移动到构造函数中.
class CustomCardView : FrameLayout {
constructor(context: Context) :
this(context,null)
constructor(context: Context,attrs: AttributeSet) :
this(context,0)
constructor(context: Context,defStyleAttr: Int) :
super(context,defStyleAttr) {
LayoutInflater.from(context).inflate(R.layout.view_custom_card,R.styleable.custom_card_view)
if (a.hasValue(R.styleable.custom_card_view_command)) {
var myString = a.getString(R.styleable.custom_card_view_command)
}
}
}
}