-
Notifications
You must be signed in to change notification settings - Fork 55
InvalidEditText
ZieIony edited this page Oct 25, 2019
·
1 revision
Supporting custom states is very simple as it involves only adding a state attribute and overriding one method responsible for assembling a state array. You can read more about custom states here.
I prepared a custom EditText
class supporting a state of being invalid. I started with a simple view extending AppCompatEditText and added a valid
boolean property.
class InvalidEditText @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : AppCompatEditText(context, attrs) {
private var _valid: Boolean = false
var valid
get() = _valid
set(value) {
if (_valid == value)
return
_valid = value
refreshDrawableState()
}
}
The important thing is to call refreshDrawableState()
so the view is refreshed after changing the invalid
property. Then I added a custom attribute to attrs.xml
:
<attr name="guide_state_invalid" format="boolean" />
The key part is to add the new attribute to the state array when the view is in an invalid state.
class InvalidEditText @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : AppCompatEditText(context, attrs) {
// ..
override fun onCreateDrawableState(extraSpace: Int): IntArray {
if (!valid) {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
drawableState[drawableState.size - 1] = R.attr.guide_state_invalid
return drawableState
}
return super.onCreateDrawableState(extraSpace)
}
}
Now I can create a color selector :
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:color="@color/carbon_red_400" app:guide_state_invalid="true" />
<item android:color="?android:attr/textColorPrimary" />
</selector>
And use it with InvalidEditText
like this:
<com.github.zieiony.guide.invalidedittext.InvalidEditText
android:id="@+id/invalidEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="at least 6 characters"
android:textColor="@color/text_color_selector"/>