Software-defined underline color for EditText

I have a regular 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 filter to a background color as follows:

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

However, I do not see any changes when the application starts. Change the background itself:

 editText.setBackground(color) 

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

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

+2
android
source share
4 answers

You need to set backgroundTintList (or supportBackgroundTintList ) in EditText to an instance of ColorStateList containing only the color you want to change the hue to. An easy way to do this with backward compatibility is as follows:

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

This will give EditText desired underline color.

+8
source share
Answer to

@degs is correct. But just add one small note: now AppCompatEditText#setSupportBackgroundTintList annotated with @RestrictTo(LIBRARY_GROUP) , which means:

Limit code usage in the same library group

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

 ColorStateList colorStateList = ColorStateList.valueOf(color); ViewCompat.setBackgroundTintList(editText, colorStateList); 
+11
source share

Changing the color of an EditText underline can be done programmatically using the ColorFilter class and other ways, but you will have an API level problem. The best way to solve these problems is to use a 9-patch image.

https://romannurik.imtqy.com/AndroidAssetStudio/nine-patches.html go here, download a set of drawings and put them in your folder with the ability to move and programmatically change the background EditText ( et_joker.setBackground(your_drawable); ) This will work independently from the API level.

0
source share

This is cleaner and works well for me:

  • Create a drawable called underline.xml by changing the color of the line of your choice.

 <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:top="-5dp" android:right="-5dp" android:left="-5dp"> <shape android:shape="rectangle" > <solid android:color="@android:color/transparent" /> <stroke android:width="1dp" android:color="@color/YOUR_LINE_COLOUR" /> </shape> </item> </layer-list> 
  1. Then use the following code in a TextEdit or AutocompleteTextView object:

 editText.setBackground(this.getResources().getDrawable(R.drawable.underline)); 
0
source share

All Articles