Android: Different colours for different characters in EditText

情到浓时终转凉″ 提交于 2019-11-28 10:33:37

问题


Thank you in advance for any responses.

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

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.


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/8043767/android-different-colours-for-different-characters-in-edittext

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