简体   繁体   English

多色EditText

[英]EditText in multi-color

I am working on an Android application. 我正在开发一个Android应用程序。

Now I want take input from user into an EditText. 现在,我想将用户输入的内容输入到EditText中。 I want display the text after the last fullstop in black color and text before last full stop in red color. 我想以黑色显示最后一个句号之后的文本,以红色显示最后一个句号之前的文本。

For example, If user types below sentence in EditText: 例如,如果用户在EditText中键入以下句子:

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

I want to show the 'I love Android ' in black and first parts of the sentence in red. 我想用黑色显示“我爱Android”,用红色显示句子的第一部分。

Is there any way to do that? 有什么办法吗?

Use SpannableString to apply attributes to your text. 使用SpannableString将属性应用于文本。 Here blog entry you may want to read: http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring . 您可能想在这里阅读博客条目: http : //www.chrisumbel.com/article/android_textview_rich_text_spannablestring

Listen to changes in text by: 通过以下方式收听文本更改:

    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) {}
    });   

then declare a function to colorize text by using the tutorial which WebnetMobile linked to. 然后使用WebnetMobile链接到的教程声明一个为文本着色的函数。

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

flag boolean variable colorHasSet should be defined to prevent stackOverflowException. 标志boolean变量colorHasSet应该定义为防止stackOverflowException。

this is not a complete WYSIWYG editor with instant colored text, and you should do some hacks to make it complete and suitable to your needs, that is left to be done by yourself. 这不是具有即时彩色文本的完整的所见即所得(WYSIWYG)编辑器,您应该做一些破解使其完整并适合您的需求,这些工作完全由您自己完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM