我想使用我的error
属性来更改自定义控件的背景颜色
我在attrs.xml
<resources>
<declare-styleable name="InfoControl">
<attr name="title" format="string"/>
<attr name="value" format="string"/>
<attr name="error" format="boolean"/>
</declare-styleable>
</resources>
从ConstraintLayout继承的我的自定义类
class InfoControl @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : ConstraintLayout(context, attrs, defStyle) {
private var error = false
init {
LayoutInflater.from(context)
.inflate(R.layout.info_control, this, true)
val att = context.obtainStyledAttributes(attrs, R.styleable.InfoControl)
tv_title.text = att.getString(R.styleable.InfoControl_title)
tv_value.text = att.getString(R.styleable.InfoControl_value)
error = att.getBoolean(R.styleable.InfoControl_error, false)
att.recycle()
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
return if (error) {
val errorState = super.onCreateDrawableState(extraSpace + 1)
View.mergeDrawableStates(errorState, intArrayOf(R.attr.error))
}
else {
super.onCreateDrawableState(extraSpace)
}
}
fun setStateError(isError: Boolean) {
if (error != isError) {
error = isError
refreshDrawableState()
}
}
}
还有我在xml file
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
app:error="true"
android:drawable="@drawable/background_control_error"/>
<item app:error="false"
android:drawable="@drawable/background_control"/>
</selector>
自定义控件的布局(我删除了不重要的行)
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@drawable/background_control_selector">
要使用此布局
<com.example.package.InfoControl
app:error="false"
app:title="The title"
app:value="1234"
android:id="@+id/ic_id"
style="@style/style_info_control"/>
现在,我的风格很好,但是如果我更改错误属性,背景也不会改变
如果更改选择器中项目的顺序,则无效