【问题标题】:How to create EditText hint as Text with image in android如何在android中将EditText提示创建为带有图像的文本
【发布时间】:2013-12-13 13:51:02
【问题描述】:

如何在 android 中使用文本和图像创建 EditText 提示/占位符。我是这样写的

<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 不为空隐藏提示文本和图像

【问题讨论】:

  • 我怎样才能在提示和可绘制左侧之间设置一些差距
  • 你可以像这样使用 android:drawablePadding="10dp" 属性。
  • ImageSpan 应该可以解决问题。

标签: android image hint


【解决方案1】:

您可以像在 xml 中一样设置drawableLeft,然后将addTextChangedListener 添加到您的 EditText。发生键入时,将警告此侦听器,如果 textsize 大于 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);
    }
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-06-19
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2013-06-29
      • 2011-08-10
      • 2020-12-09
      相关资源
      最近更新 更多