Android: Different colours for different characters in EditText

自闭症网瘾萝莉.ら 提交于 2019-11-29 16:42:10

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

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.

You probably want to wrap each letter in its own ForegroundColorSpan. Add a TextWatcher and apply the Spannables as the text is edited.

You best shot is probably overriding EditText and writing your own draw(). But this way lies madness, as it usually is with overriding built-in view classes.

Arkadiusz Cieśliński

If I were You I would better use the InputFilter for it. setText() in textWatcher{} onTextChange() has some issues (eg. on a softkeyboard you can't select an national letter).

Some issue with the TextWatcher

Documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!