問題描述
提前感謝您的任何回復.
Thank you in advance for any responses.
我正在嘗試在我的 Android 應用程序中添加一個 EditText,它對輸入的不同字符具有不同的顏色.
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中不同字符的不同顏色的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!