如何在android中创建EditText提示为Text with image



如何使用Text&android中的图像。我这样写

<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"/>

在这里我们可以看到图片&edittext中的文本(提示),但即使用户在该字段中输入了内容,图像仍然可见。我的要求是,如果在EditText中没有文本,则显示带图像的提示,如果EditText不为空,则隐藏提示文本和图像

您可以像在xml中那样设置一个drawableLeft,并将一个addTextChangedListener添加到EditText中。当键入时,将警告此侦听器,如果文本大小大于0,则可以签入侦听器。如果是,那么只需将xml中以编程方式分配的drawableLeft设置为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);
    }
}

我是通过将EditText放入FrameLayout中,然后在FrameLayout内包含TextView来实现这一点的。TextView充当提示文本。我在TextView上有一个drawableStart属性。当用户开始键入时,TextView将使用与Dion接受的答案中类似的代码隐藏。

最新更新