的EditText - 文字更改背景颜色(只有文本 - 而不是整个视图) [英] EditText - change background color of text (and only text - not the whole view)

查看:1235
本文介绍了的EditText - 文字更改背景颜色(只有文本 - 而不是整个视图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个用户在一个EditText信息,并且移动到下一的EditText,如下所示的信息被高亮显示:

When a user enters information in an EditText, and moves to the next EditText, the information is highlighted as shown below:

在$ C $下这样的:

The code for this:

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 的方法是这样的:

的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:

<一个href="http://developer.android.com/reference/android/text/style/BackgroundColorSpan.html">http://developer.android.com/reference/android/text/style/BackgroundColorSpan.html

要使用的跨越,你需要建立一个 SpannableString ,你可以用做一个 SpannableStringBuilder

To use spans you need to build a SpannableString which you can do using a SpannableStringBuilder:

<一个href="http://developer.android.com/reference/android/text/SpannableStringBuilder.html">http://developer.android.com/reference/android/text/SpannableStringBuilder.html

这篇关于的EditText - 文字更改背景颜色(只有文本 - 而不是整个视图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆