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.
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.
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).
来源:https://stackoverflow.com/questions/8043767/android-different-colours-for-different-characters-in-edittext