我有一个自定义视图与一些自定义属性。
class SomeCustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
很清楚如何在这里检索属性:
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.SomeCustomView, 0, 0)
try {
someAttribute = a.getInt(R.styleable.SomeCustomView_swomeAttribute, DEFAULT_VALUE)
//...
} finally {
a.recycle()
}
View的布局充满了
inflate(context, R.layout.some_view, this)
问题是R.layout.some_view
包含另一个自定义视图作为其子项之一,不应该暴露(ChildCustomView
)。
问题是如何检索SomeCustomView
中ChildCustomView
的属性?
在子视图膨胀之前,您无法从父级检索属性。
所以你必须将它们存储在ChildCustomView字段和SomeParentCustomView的onFinishInflate()
中,使用属性访问或getter检索它们。