I have severalEditTextfields in my layout xml. All of them follow this pattern:
<EditText
    style="@style/EditText"
    android:id="@+id/email"
    android:hint="Email Address"
    android:inputType="textEmailAddress"
    android:drawableEnd="@drawable/icon1" />
If this field gains focus, I want to set the drawableIcon to icon1 and if it loses focus, I want to set it to icon2.
I know I can do it using setOnFocusChangeListener in my activity. 
But I want to ask is it possible to do it using XML only?
It can be easily done using simple selectors once you create a custom drawable.
Check this tutorial where it applies what you want to a Button.
http://www.mkyong.com/android/android-imagebutton-selector-example/
Something like this should work for you:
<EditText
    style="@style/EditText"
    android:id="@+id/email"
    android:hint="Email Address"
    android:inputType="textEmailAddress"
    android:background ="@drawable/customDrawableIcon" />
res/drawable/customDrawableIcon.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon1"
          android:state_focused="true" />
    <item android:drawable="@drawable/icon2"
          android:state_focused="false" />
</selector>
I think it is possible, you need to create a selector xml for Edittext in your drawable folder, check this post he gave a good answer for this.
https://stackoverflow.com/a/14543476/1007087
You can use selector and change the state_focused drawable
    <?xml version="1.0" encoding="utf-8"?>
     <selector xmlns:android="http://schemas.android.com/apk/res/android" >
      <item android:state_focused="true" android:drawable="@drawable/focusedIcon"/>
      <item android:drawable="@drawable/normalicon"/>
    </selector>
so now the android:drawableEnd should refer to the previous selector.
Hope this will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With