Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change drawable when a field gains focus

Tags:

android

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?

like image 794
Akeshwar Jha Avatar asked Feb 07 '16 12:02

Akeshwar Jha


3 Answers

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>
like image 162
GoRoS Avatar answered Oct 18 '22 02:10

GoRoS


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

like image 2
Aziz Avatar answered Oct 18 '22 03:10

Aziz


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.

like image 2
M.Khouli Avatar answered Oct 18 '22 02:10

M.Khouli