自定义EditText的setError图标

21

我想给我的EditText设置一个setError方法,使用自定义图标而不是默认的Android图标。所以我尝试了这个:

((EditText)findViewById(R.id.edtTitle)).setError(getResources().getText(R.string.errEmptyTitle), 
         getResources().getDrawable(R.drawable.ico_warning_small);

它向我显示自定义消息,但没有显示自定义图标。 我也尝试过这个:

Drawable warning = (Drawable)getResources().getDrawable(R.drawable.ico_warning_small);
((EditText)findViewById(R.id.edtTitle))
      .setError(getResources().getText(R.string.errEmptyTitle), warning);
几乎一样,但我还是决定试一试。然而这也没有帮助——我仍然看不到图标。 我尝试使用其他的Android系统图标,只是想看看是否能看到它们,但同样也看不到。 那我做错了什么?有没有办法设置自定义图标呢?

1
请参见此处:https://dev59.com/zGox5IYBdhLWcg3ww3CV - Steelight
@Steelight非常感谢,它起作用了!您能否将您的评论变成答案,这样我就可以接受它了吗? - Igal
4个回答

48

在使用 setError 之前,您需要设置 drawable 的边界。

drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
editText.setError("error", drawable);

这解决了我的问题。谢谢。 - Bill Mote
谢谢 - 花了一个小时在这上面! - Mike6679
使用画布和画笔创建新的可绘制对象时,getIntrinsicWidth和getIntrinsicHeight返回-1,有什么线索吗? - buradd

8
如果您不想显示任何图标,请使用以下代码:
editText.setError("error", null);

4

3
    Drawable customErrorDrawable = getResources().getDrawable(R.drawable.error_icon);
        customErrorDrawable.setBounds(0, 0, customErrorDrawable.getIntrinsicWidth(), customErrorDrawable.getIntrinsicHeight());


 editText.setError("please enter data",customErrorDrawable);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接