Programmatically changing underline color of EditText

前端 未结 4 1096
既然无缘
既然无缘 2021-01-04 09:56

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



        
相关标签:
4条回答
  • 2021-01-04 10:27

    @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);
    
    0 讨论(0)
  • 2021-01-04 10:30

    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.

    0 讨论(0)
  • 2021-01-04 10:51

    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.

    0 讨论(0)
  • 2021-01-04 10:51

    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

    0 讨论(0)
提交回复
热议问题