EditText Hint Text and Icon

2019-07-01 14:12发布

问题:

I am trying to create an EditText with the hint as icon and text both together. But hint text goes to the center but I want hint text to be left aligned so that there should only be a tab space (gap) between hint icon and hint text.

This is what I have tried:

<EditText
        android:id="@+id/emailAddressInput"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:ems="10"
        android:layout_marginTop ="20dp"
        android:layout_marginLeft ="20dp"
        android:layout_marginRight ="20dp"
        android:background="@drawable/rounded_edge"
        android:drawableLeft="@drawable/email_box"
        android:hint="e-mail address"
        android:gravity="left|center_vertical"
        android:maxLength="100"
        android:inputType="textEmailAddress" />

Any idea how can I achieve desired result?

回答1:

ImageSpan is the best way to do this.

But you got to do it through Java code.

ImageSpan imageHint = new ImageSpan(mContext, R.drawable.icon_hint);
SpannableString spannableString = new SpannableString("_I'm the hint");
spannableString.setSpan(imageHint, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
mEditor.setHint(spannableString);


回答2:

Okay so after a little debugging, I found out that the image size was taking that much space, I have cropped the image to smaller size and it worked.



回答3:

Add

android:gravity="top"

to your EditText.