I'm trying to set a custom drawable to a EditText as expected below:
So I wrote this custom drawable:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingBottom="12dp"
android:paddingLeft="36dp"
android:paddingRight="12dp"
android:paddingTop="12dp">
<item>
<shape>
<corners android:radius="6dp"/>
<solid android:color="@android:color/white"/>
<stroke
android:width="1dp"
android:color="#BBBBBB"/>
</shape>
</item>
<item
android:width="32dp"
android:gravity="left">
<shape android:shape="rectangle">
<size android:width="32dp"/>
<corners
android:bottomLeftRadius="6dp"
android:topLeftRadius="6dp"/>
<solid android:color="#AAAAAA"/>
</shape>
</item>
<item android:left="8dp">
<bitmap
android:gravity="left"
android:src="@drawable/ic_email"
android:tileMode="disabled"/>
</item>
</layer-list>
The result in preview is quite good (except different corner size, not handled by Android Studio)
But in device, it totally not works... The second item is stretched and does not respect the width attribute.
I know, I can do it with a 9-patch, but I want to know if is it possible with drawables?
Managed to do it with a single background drawable and a compound drawable on the EditText.
bg_edittext_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<corners android:radius="6dp" />
<solid android:color="@android:color/white" />
</shape>
</item>
<item>
<shape>
<solid android:color="#AAAAAA" />
<corners android:radius="6dp" />
</shape>
</item>
<item
android:left="34dp">
<!-- left is icon size + 2x side padding around icon-->
<!-- 18 + 8 + 8 -->
<shape>
<solid android:color="@android:color/white" />
<corners android:radius="6dp"
android:topRightRadius="6dp"
android:topLeftRadius="0dp"
android:bottomRightRadius="6dp"
android:bottomLeftRadius="0dp"/>
</shape>
</item>
<item>
<shape>
<corners android:radius="6dp" />
<solid android:color="@android:color/transparent" />
<stroke
android:width="1dp"
android:color="#BBBBBB" />
</shape>
</item>
</layer-list>
In your layout, use it like that:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_edittext_icon"
android:inputType="textEmailAddress"
android:drawableLeft="@drawable/ic_email_white_18dp"
android:drawablePadding="20dp"
android:paddingLeft="8dp"
android:paddingRight="12dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:hint="Email"
/>
With paddingLeft
the icon padding inside the grey box and drawablePadding
the padding inside the grey box + padding of the edit zone.
Here is the result from Genymotion (aka, real device):
Hope you like it !
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