EditText - change background color of text (and only text - not the whole view)(EditText - 更改文本的背景颜色(只有文本 - 不是整个视图))
问题描述
当用户在 EditText 中输入信息,并移动到下一个 EditText 时,信息会高亮显示,如下所示:
When a user enters information in an EditText, and moves to the next EditText, the information is highlighted as shown below:
代码:
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundColor(Color.WHITE);
((EditText) v).setTextColor(Color.BLACK);
} else {
//v.setBackgroundColor(Color.LTGRAY); //also works like this
((EditText) v).setBackgroundColor(Color.LTGRAY);
((EditText) v).setTextColor(Color.BLACK);
}
}
});
在 onCreate
方法中调用如下:
Which is called in the onCreate
method like this:
edittext = (EditText) findViewById(R.id.editText1);
但是,如果背景颜色只应用于文本本身而不是视图,那就更好了,就像这样(来自 gmail 应用程序):
However, It would be much better if the background color only applied to the text itself, rather than the view, like this (from the gmail app):
是否有人对如何将背景颜色仅应用于文本(而不是整个 EditText 视图)有任何建议?
Does anybody have any suggestions on how to apply the background color to the text only (not the whole EditText view) as above?
谢谢.
推荐答案
您可以使用 BackgroundColorSpan
来实现您想要的.您可以在此处找到更多信息:
You can achieve what you want by using a BackgroundColorSpan
. You can find more information here:
http://developer.android.com/reference/android/text/style/BackgroundColorSpan.html
要使用 span,您需要构建一个 SpannableString
,您可以使用 SpannableStringBuilder
:
To use spans you need to build a SpannableString
which you can do using a SpannableStringBuilder
:
http://developer.android.com/reference/android/text/SpannableStringBuilder.html一个>
这篇关于EditText - 更改文本的背景颜色(只有文本 - 不是整个视图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:EditText - 更改文本的背景颜色(只有文本 - 不是整


- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01