How to change focus color of EditText in Android

前端 未结 3 775
梦毁少年i
梦毁少年i 2020-11-27 02:39

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 con

相关标签:
3条回答
  • 2020-11-27 03:29
    <?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>
    
    0 讨论(0)
  • 2020-11-27 03:36

    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"
    
    0 讨论(0)
  • 2020-11-27 03:45

    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)
    }
    
    0 讨论(0)
提交回复
热议问题