EditText采用多色

时间:2012-09-11 11:27:11

标签: android android-layout

我正在开发Android应用程序。

现在我想从用户输入EditText。 我希望在最后一个完整停止之后以红色显示最后一个完整停止之后的文本,并在最后一个完全停止之前以红色显示文本。

例如,如果用户在EditText中输入以下句子:

'my name is john.I am from India.I Love Android'

我想以黑色显示“我爱Android”,并以红色显示句子的第一部分。

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:3)

使用SpannableString将属性应用于文字。您可以在这里阅读博客文章:http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring

答案 1 :(得分:1)

通过以下方式收听文字中的更改:

    editText.addTextChangedListener(new TextWatcher() { 
        public void afterTextChanged(Editable s) { 
            if (!colorHasSet) {
                makeColorText();
            }
            colorHasSet = false;
        }
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
    });   

然后使用WebnetMobile链接到的教程声明一个颜色化文本的函数。

public void makeColorText() {
     SpannableString ss = new SpannableString(textEdit.getText());
    // customize ss here
    // ...
    colorHasSet = true;
    editText.setText(ss);
}
应该定义

标志布尔变量colorHasSet以防止stackOverflowException。

这不是一个完整的WYSIWYG编辑器,带有即时彩色文本,你应该做一些黑客来使它完整并适合你的需要,这是由你自己做的。