您的位置:首页 > 移动开发 > Android开发

Android中EditText的setError文字不显示的问题

2016-04-27 19:40 405 查看

现象

Android系统提供的控件EditText,使用其方法setError时,会出现错误框显示但是文字不显示的问题。原因是系统部分主题的setError文字和背景都是白色,例如系统自带的几个light的theme。

解决方法

修改主题

既然是主题的问题,那我们可以尝试自定义主题并进行适当的修改,在
res/values/styles.xml
文件中,在自定义主题里加入一个item:


<item name="android:textColorPrimaryInverse">@android:color/primary_text_light</item>



完整文件内容如下:


<resources xmlns:android="http://schemas.android.com/apk/res/android">
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:textColorPrimaryInverse">@android:color/primary_text_light</item></style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
</style>
<style name="LoginFormContainer">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:padding">16dp</item>
</style>

<style name="edittext_style" parent="@android:style/Widget.EditText">
<item name="android:background">@drawable/bg_edittext</item>
<item name="android:paddingLeft">10dip</item>
<item name="android:paddingTop">8dip</item>
<item name="android:paddingBottom">8dip</item>
</style>
</resources>


这样,提示的内容颜色会变为黑色。

参考资料:http://blog.csdn.net/yangmingysc/article/details/8543693

当然,换个其他的主题也是可以的,简单粗暴!

使用Html格式文本

Android提供了
Html.fromHtml()
方法,可以将部分html语言片段转换成字符序列对象。同时setError(CharSequence c)方法的参数是字符序列对象,推荐使用Html格式文本加载进去,显示错误。

使用方法也比较简单:

CharSequence html1 = Html.fromHtml("<font color='blue'>出错</font>"); //任意长度内容均可
//Spanned html2 = Html.fromHtml("出错"); //纯文本不可取-内容将不会显示
editText.setError(html1);
//editText.setError(html2);

需要注意的是:

参数必须是CharSequence/Spanned类型变量;
fromHtml()方法参数必须包含HTML标准标签;
报错内容不要过长,尽量简短,否则UI叠层架构中会出现覆盖现象,而导致不显示内容。

参考资料:http://bbs.csdn.net/topics/390304638

扩展

关于使用Html语言片段解决的方法比较简单实用,并且我们使用的聊天工具中输入框的表情也可以通过这种方式来解决。稍后会对表情相关的开发做一些研究,感兴趣的朋友可以持续关注。

迫不及待的同学可以先参考一下下面的资料(暂未试验):
http://www.iteedu.com/handset/android/spannablediary/showhtmlimage.php

原文地址: http://www.codefrom.com/c/101
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  setError