我試圖在輸入文本時將字體顏色應用於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