【发布时间】:2021-06-12 12:57:50
【问题描述】:
我的自定义视图类:
class SearchBox : FrameLayout {
constructor(context: Context) : super(context)
constructor(
context: Context,
attrs: AttributeSet?
) : this(context, attrs, R.attr.searchBoxStyle)
constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : this(
context,
attrs,
defStyleAttr,
R.style.SearchBoxStyle
)
constructor(
context: Context,
attrs: AttributeSet?,
@AttrRes defStyleAttr: Int,
@StyleRes defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes) {
inflate(context, R.layout.search_box, this)
val a = context.obtainStyledAttributes(attrs, R.styleable.SearchBox, defStyleAttr, defStyleRes)
a.recycle()
}
}
样式声明:
<style name="SearchBoxStyle" parent="">
<item name="background">@color/black</item>
</style>
Styleable(暂时为空,我会使用平台属性,例如“背景”):
<declare-styleable name="SearchBox">
</declare-styleable>
问题 永远不会设置“背景”属性。
如何为自定义视图定义简单的默认样式?
更新
<declare-styleable name="SearchBox">
<attr name="background" format="reference" />
</declare-styleable>
constructor(
context: Context,
attrs: AttributeSet?,
@AttrRes defStyleAttr: Int,
@StyleRes defStyleRes: Int
) : super(context, attrs, defStyleAttr, defStyleRes) {
inflate(context, R.layout.search_box, this)
val a = context.obtainStyledAttributes(attrs, R.styleable.SearchBox, defStyleAttr, defStyleRes)
val background = a.getDrawable(R.styleable.SearchBox_background)
background?.apply { setBackground(this) }
a.recycle()
}
这是正确的方法吗?
我希望有一种方法可以做到,即使不重新定义平台的所有属性然后手动应用它们。
【问题讨论】:
标签: android styles android-custom-view