Kotlin:如何访问自定义视图的Attrs

我在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, 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块的内容用三个参数移动到构造函数中。

 class CustomCardView : FrameLayout { constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { 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) } } } } 

调整你的代码,我想你也可以做这样的事情:

 class CustomCardView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : FrameLayout(context, attrs, defStyleAttr) { constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) 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) } a.recycle() } } }