0

我正在开发一个 Android 应用程序。

现在我想将用户的输入输入到 EditText 中。我想在最后一个句号之后以黑色显示文本,在最后一个句号之前以红色显示文本。

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

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

我想用黑色显示“我爱 Android”,用红色显示句子的前半部分。

有没有办法做到这一点?

4

2 回答 2

3

用于SpannableString将属性应用到您的文本。您可能想阅读这里的博客条目:http: //www.chrisumbel.com/article/android_textview_rich_text_spannablestring

于 2012-09-11T11:28:17.720 回答
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。

这不是一个带有即时彩色文本的完整所见即所得编辑器,您应该做一些技巧以使其完整并适合您的需求,这由您自己完成。

于 2012-09-11T12:05:08.757 回答