how to change focus color of EditText in Android

2019-01-06 10:28发布

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? Can anyone help me in sorting out this issue? Thanks in advance,

3条回答
Fickle 薄情
2楼-- · 2019-01-06 11:05
<?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>
查看更多
虎瘦雄心在
3楼-- · 2019-01-06 11:18

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)
}
查看更多
做个烂人
4楼-- · 2019-01-06 11:19

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"
查看更多
登录 后发表回答