简体   繁体   中英

How to change focus color of EditText in Android

How can I change the focus color (orange) on an EditText box?

The focus color is a small rim around the entire control and is bright orange when the control has focus. How can I change the color of that focus to a different color?

You'll have to create/modify your own NinePatch image to replace the default one, and use that as the background of your EditText. If you look in your SDK folder, under your platform, then res/drawable, you should find the NinePatch image for the EditText focus state. If that's all you want to change, you can just pull it into Photoshop, or whatever image editing software you have, and change the orange color to a color of your choosing. Then save that into your drawable folder, and build a new StateListDrawable, for example something like the below:

edittext_modified_states.xml

<?xml version="1.0" encoding="utf-8"?>
<selector 
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item 
        android:state_pressed="true"
        android:drawable="@android:drawable/edittext_pressed" 
        /> <!-- pressed -->    
    <item 
        android:state_focused="true"
        android:drawable="@drawable/edittext_focused_blue" 
        /> <!-- focused -->    
    <item 
        android:drawable="@android:drawable/edittext_normal" 
        /> <!-- default -->
</selector>

I don't know offhand the actual names for the default NinePatches for the EditText, so replace those as necessary, but the key here is to just use the @android:drawable images for the ones you haven't modified (or you can copy them over to your project's drawable folder), and then use your modified drawable for your focused state.

You can then set this StateListDrawable as the background for your TextView, like so:

<TextView
    android:background="@drawable/edittext_modified_states"
<?xml version="1.0" encoding="utf-8"?>
<selector 
xmlns:android="http://schemas.android.com/apk/res/android"
>
    <item 
      android:state_pressed="true"
      android:color="colorcode" 
    /> <!-- pressed -->    
    <item 
       android:state_focused="true"
       android:color="colorcode"
    /> <!-- focused -->    
    <item 
           android:color="colorcode"
    /> <!-- default -->
</selector>

You dont need to create xml drawables. It may be more simple in code. Example in kotlin:

editText.onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
    // colorLine, colorLineFocus is vars of ColorStateList
    ViewCompat.setBackgroundTintList(editText, if (hasFocus) colorLineFocus else colorLine)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM