在选择器中使用自定义属性

时间:2019-04-09 11:14:44

标签: android kotlin

我想使用我的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"/>

结果

现在,我的风格很好,但是如果我更改错误属性,背景也不会改变

测试

如果更改选择器中项目的顺序,则无效

0 个答案:

没有答案