degs
degs

Reputation: 1072

Programmatically changing underline color of EditText

I have an ordinary EditText field that I would like to programmatically change the underline color for.

<EditText
    android:id="@+id/edit_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPassword"/>

Other answers suggest changing the background color filter like so:

editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);

However, I don't see any change when I run the app. Changing the background itself:

editText.setBackground(color)

changes the entire EditText to color - not what I want!

How do I programmatically change the underline color for an EditText, AppCompatEditText or TextInputEditText? I am using version 25.0.1 of the Support Library.

Upvotes: 15

Views: 25265

Answers (4)

degs
degs

Reputation: 1072

You need to set the backgroundTintList (or supportBackgroundTintList) on the EditText to an instance of ColorStateList containing only the color you wish to change the tint to. An easy way to do this in a backwards-compatible way looks like this:

ColorStateList colorStateList = ColorStateList.valueOf(color);
editText.setSupportBackgroundTintList(colorStateList);

This will give the EditText the desired underline color.

Upvotes: 26

Arnold Laishram
Arnold Laishram

Reputation: 1881

I couldn't make it working with the above solution when the edit text is in focus.

I had to add colorControlActivated in the theme.

<style name="StyledTilEditTextTheme">
   <item name="colorControlNormal">@color/greyLight</item>
   <item name="colorControlActivated">@color/gray_ccc</item>
</style>

This worked for me

Upvotes: 0

Aaron He
Aaron He

Reputation: 5549

@degs's answer is correct. But just add one little note: the AppCompatEditText#setSupportBackgroundTintList is now annotated with @RestrictTo(LIBRARY_GROUP) which means:

Restrict usage to code within the same group of libraries

Instead use ViewCompat#setBackgroundTintList. So in your example, it should look like this:

ColorStateList colorStateList = ColorStateList.valueOf(color);
ViewCompat.setBackgroundTintList(editText, colorStateList);

Upvotes: 38

Rushi Ayyappa
Rushi Ayyappa

Reputation: 2848

Changing the color of EditText underline programmatically can be done using ColorFilter class and other ways but you will have an API level problem. The best way to resolve these type of issues is by using a 9-Patch image.

https://romannurik.github.io/AndroidAssetStudio/nine-patches.html go here download a set of drawables and put them in your drawable folder and change the background of EditText programmatically( et_joker.setBackground(your_drawable); ) This will work irrespective to API levels.

Upvotes: 0

Related Questions