'TextInputLayout change start icon tint color on focus
How to change startIconDrawable color when the focus is on the TextInputEditText
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="rtl"
app:boxBackgroundColor="@color/white"
app:endIconMode="clear_text"
app:startIconDrawable="@drawable/person_24dp">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:hint="family"
android:imeOptions="actionDone"
android:singleLine="true"
android:textSize="@dimen/mediumTextSize" />
</com.google.android.material.textfield.TextInputLayout>
Solution 1:[1]
Kotlin:
textInputEditText.setOnFocusChangeListener { _, hasFocus ->
val color = if (hasFocus) Color.BLUE else Color.GRAY
textInputLayout.setStartIconTintList(ColorStateList.valueOf(color))
}
Java:
textInputEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
int color = hasFocus ? Color.BLUE : Color.GRAY;
textInputLayout.setStartIconTintList(ColorStateList.valueOf(color));
}
});
Java code can be simplified using lambda expression.
Solution 2:[2]
You can solve it by BindingAdapter
@BindingAdapter("startIconTintOnFocus")
fun TextInputLayout.startIconTintOnFocus(textInputEditTextId: Int) {
val et = findViewById<TextInputEditText>(textInputEditTextId)
et.setOnFocusChangeListener { _, hasFocus ->
val color = if (hasFocus) ContextCompat.getColor(context, R.color.colorAccent) else ContextCompat.getColor(context, R.color.red)
this.setStartIconTintList(ColorStateList.valueOf(color))
}
}
set the startIconTintOnFocus
in TextInputLayout
and send TextInputEditText
's id to it
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/outlinedTextField"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:startIconTint="@color/red"
startIconTintOnFocus="@{@id/textInputEditText}"
app:startIconDrawable="@drawable/ic_phone_android_24dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/textInputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/textColorPrimary"
android:textSize="@dimen/mediumTextSize"/>
</com.google.android.material.textfield.TextInputLayout>
thank's to @miel3k
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |