How to create EditText hint as Text with image in android

核能气质少年 提交于 2019-12-30 08:14:48

问题


How to create EditText hint/placeholder with Text & image in android. I write like this

<EditText  
    android:id="@+id/name" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content"     
    android:lines="1"
     ................................
...............................

android:drwableLeft="@drawable/image1"
android:hint="enter name here"/>

Here we can see image & text (hint) within edittext but image still visible even after user enters something in that field. My requirement is if there is no text in EditText show hint with image, if EditText is not empty hide hint text and image


回答1:


What you can do is set an drawableLeft as you did in your xml and add an addTextChangedListener to your EditText. When typing occurs this listener will be warned and you can check in the listener if the textsize is bigger than 0. If so, then just set the drawableLeft assigned in the xml programmatically to null.

@Override
public void afterTextChanged(Editable s) {
    if(s.toString().length() > 0) {
        editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
    } else {
        //Assign your image again to the view, otherwise it will always be gone even if the text is 0 again.
        editText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.image, 0, 0, 0);
    }
}



回答2:


I did this by placing my EditText inside a FrameLayout, and then also including a TextView inside the FrameLayout. The TextView serves as the hint text. I have a drawableStart attribute on the TextView. When the user starts typing the TextView is hidden using code similar to that in the accepted answer from Dion.



来源:https://stackoverflow.com/questions/20250638/how-to-create-edittext-hint-as-text-with-image-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!