当计数器超过最大长度时,请勿更改TextInputLayout背景

时间:2019-10-21 11:45:22

标签: android kotlin android-edittext counter textinputlayout

当计数器超过最大长度时,我希望我的编辑文本具有正常背景且没有红色。而且我想在文本超过颜色时将其颜色更改为红色。

Now it looks like this:

I want it to look like this

我尝试使用此解决方案here,但是当计数器超出方法setError(error: CharSequence?)时,不会被调用,并且无法覆盖方法updateCounter(length: Int)自己手动设置错误。 / p>

class NoChangingBackgroundTextInputLayout : TextInputLayout {

    private val backgroundDefaultColorFilter: ColorFilter?
        get() {
            var defaultColorFilter: ColorFilter? = null
            if (editText != null && editText!!.background != null)
                defaultColorFilter = DrawableCompat.getColorFilter(editText!!.background)
            return defaultColorFilter
        }

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    override fun setError(error: CharSequence?) {
        val defaultColorFilter = backgroundDefaultColorFilter
        super.setError(error)
        //Reset EditText's background color to default.
        updateBackgroundColorFilter(defaultColorFilter)
    }

    override fun drawableStateChanged() {
        val defaultColorFilter = backgroundDefaultColorFilter
        super.drawableStateChanged()
        //Reset EditText's background color to default.
        updateBackgroundColorFilter(defaultColorFilter)
    }

    private fun updateBackgroundColorFilter(colorFilter: ColorFilter?) {
        if (editText != null && editText!!.background != null)
            editText!!.background.colorFilter = colorFilter
    }
}

我的XML布局如下:

<NoChangingBackgroundTextInputLayout
    android:id="@+id/textInputLayout"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    app:counterEnabled="true"
    app:counterMaxLength="250"
    app:counterTextAppearance="@style/CounterTextViewStyle"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView18">

    <android.support.design.widget.TextInputEditText
        style="@style/MyEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top|left" android:inputType="textMultiLine|textCapSentences"
        android:maxLines="10"
        android:minLines="8"
        android:paddingTop="6dp"
        android:paddingBottom="6dp"
        android:scrollbars="vertical"
        android:textSize="16sp"
        tools:text="adfsg sdg asg asd asgd asdgasdgc asgasdgasd gasd gasd sdagsadgag asg"/>

</NoChangingBackgroundTextInputLayout>

如何将edittext的文本更改为红色,以使背景保持不变?

0 个答案:

没有答案