我试图在输入文本时将字体颜色应用于EditText中的文本。然而,它只是非常不一致,这意味着有时如果你输入一个空格,那个空格之前的文本将回到默认的黑色。或者,如果我将光标置于单词的中间,并开始输入整个单词,则会更改颜色,而不仅仅是输入的文本。大胆,斜体和下划线似乎运作良好。我怎样才能保证只有我输入的文字才会受到字体颜色的影响?Android EditText:如何在输入时应用前景色跨度?
见 “的大小和颜色” 的评论如下...
contentEdit.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
//add style as the user types if a toggle button is enabled
ToggleButton boldButton = (ToggleButton) findViewById(R.id.bold);
ToggleButton emButton = (ToggleButton) findViewById(R.id.italic);
ToggleButton underlineButton = (ToggleButton) findViewById(R.id.underline);
int position = Selection.getSelectionStart(contentEdit.getText());
try{
if (position < 0){
position = 0;
}
if (position > 0){
if (styleStart > position || position > (cursorLoc + 1)){
//user changed cursor location, reset
if (position - cursorLoc > 1){
//user pasted text
styleStart = cursorLoc;
}
else{
styleStart = position - 1;
}
}
if (boldButton.isChecked()){
StyleSpan[] ss = s.getSpans(styleStart, position, StyleSpan.class);
for (int i = 0; i < ss.length; i++) {
if (ss[i].getStyle() == android.graphics.Typeface.BOLD){
s.removeSpan(ss[i]);
}
}
s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), styleStart, position, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (emButton.isChecked()){
StyleSpan[] ss = s.getSpans(styleStart, position, StyleSpan.class);
for (int i = 0; i < ss.length; i++) {
if (ss[i].getStyle() == android.graphics.Typeface.ITALIC){
s.removeSpan(ss[i]);
}
}
s.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), styleStart, position, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (underlineButton.isChecked()){
UnderlineSpan[] ss = s.getSpans(styleStart, position, UnderlineSpan.class);
for (int i = 0; i < ss.length; i++) {
s.removeSpan(ss[i]);
}
s.setSpan(new UnderlineSpan(), styleStart, position, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
//SIZE AND COLOR//////////////////////////////////////////////////////
s.setSpan(new ForegroundColorSpan(m_color), position, position, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
s.setSpan(new AbsoluteSizeSpan(m_curSize, true), position, position, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
}
catch(Exception e){
//Toast.makeText(m_ctx, m_ctx.gets, Toast.LENGTH_LONG).show();
showMessage(R.string.NOTE_WARNING_STYLE,m_utils.MSGTYPE_WARNING);
}
cursorLoc = Selection.getSelectionStart(contentEdit.getText());
}
任何人?这是我一直在寻找答案的东西... – Mike6679
您正在测试的Android版本是什么?最小和目标版本? –
2.2是最小和有针对性的 – Mike6679