Android的:不同的颜色在不同的EditText人物 [英] Android: Different colours for different characters in EditText

查看:154
本文介绍了Android的:不同的颜色在不同的EditText人物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您事先的任何答复。

Thank you in advance for any responses.

我想有一个EditText在我拥有了这是在输入不同的字符不同颜色的Andr​​oid应用程序。

I am trying to have an EditText in my Android application which has different colours for different characters which are typed in.

有关如字母A应该永远是蓝色,字母B应该永远是绿色的......等等。

For e.g. Alphabet "A" should always be blue, alphabet "b" should always be green... so on.

到目前为止,我没有能够找到一个解决方案吧。
请好心地指导我在正确的方向。

So far, I have no been able to find a solution for it. Please be kind enough to guide me in the right direction.

推荐答案

正如指出的那样,你可以为进入其应用Spannables文本。事情是这样的:

As was pointed out, you can apply Spannables to the text as it is entered. Something like this:

colorEdit.addTextChangedListener(new TextWatcher() {

    String lastText = null;

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        Log.d("", "lastText='" + lastText + "'");
        Log.d("", "s='" + s + "'");
        if (!s.toString().equals(lastText)) {
            lastText = s.toString();

            String res = "";
            char[] split = s.toString().toCharArray();
            for (char c : split) {
                String color = null;
                if (c == 'a') {
                    color = "red";
                } else if (c == 'b') {
                    color = "green";
                } else if (c == 'c') {
                    color = "blue";
                }
                // etc...
                if (color != null) {
                    res += "<font color=\"" + color + "\">" + c
                            + "</font>";
                } else {
                    res += c;
                }
            }
            int selectStart = colorEdit.getSelectionStart();
            int selectEnd = colorEdit.getSelectionEnd();
            colorEdit.setText(Html.fromHtml(res));
            colorEdit.setSelection(selectStart, selectEnd);
        }
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void afterTextChanged(Editable s) {}
});

有些事情要注意,我称之为的setText 这当然原因 onTextChanged 再次运行,所以我检查该文本实际上改变。另外,光标位置不正确保存,所以我保存和恢复这一点。

some things to note, I call setText which of course causes onTextChanged to run again, so I check that the text actually changed. Also, the cursor position was not saved correctly so I store and restore that as well.

这篇关于Android的:不同的颜色在不同的EditText人物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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