我使用下面的InputFilter過濾掉無效(十進制值大於127的ASCII),並且EditText在輸入無效字符時顯示文本兩次。我希望EditText能夠顯示有效的字符,下面是發生什麼的例子。創建擴展的ASCII字符InputFilter
- 用戶進入XYZ€中的EditText組件的屏幕提示「無效的非ASCII字符」
-EditText組件顯示在屏幕上的xyz這是我所期待的
上出現
-toast消息 - 用戶輸入有效字符,甲因此屏幕顯示XYZA
-InputFilter運行並返回XYZA但XYZXYZA出現在的EditText部件whic h不正確。它複製了XYZ
有關爲什麼在處理無效字符後複製輸入文本的任何想法?
屏幕:
<EditText android:id="@+id/editText"
android:layout_width="fill_parent" android:layout_height="120dp"
android:layout_marginTop="10dp" android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" android:maxLength="45"
android:focusable="true" android:inputType="text"
android:cursorVisible="true" android:imeOptions="actionDone"
/>
活動:
public class EditTextActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
EditText eText = (EditText) findViewById(R.id.editText);
setAsciiTextFilter();
}
private void setAsciiTextFilter() {
InputFilter filter = new InputFilter() {
int asciiNo;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
asciiNo = source.charAt(i);
if(asciiNo > 127) {
toast = mUtility.showToast("Invalid non-Ascii Character", Toast.LENGTH_SHORT);
//Replace the invalid ascii character with empty String
return source.toString().replace(source.charAt(i)+"", "");
}
}
return null;
}
};
eText.setFilters(new InputFilter[]{filter});
}
}
新嘗試:
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source instanceof SpannableStringBuilder) {
SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder)source;
for (int i = end - 1; i >= start; i--) {
char currentChar = source.charAt(i);
int ascii = currentChar;
if (ascii > 127) {
sourceAsSpannableBuilder.delete(i, i+1);
toast = mUtility.showToast("Invalid non-Ascii Character", Toast.LENGTH_SHORT);
}
}
return source;
} else {
StringBuilder filteredStringBuilder = new StringBuilder();
for (int i = 0; i < end; i++) {
char currentChar = source.charAt(i);
int ascii = currentChar;
if (ascii <= 127) {
filteredStringBuilder.append(currentChar);
}
}
return filteredStringBuilder.toString();
}
}
};
感謝您的回答。我使用了你的建議並更新了我的代碼(在新的嘗試:部分)。由於sourceAsSpannableBuilder.delete(i,i + 1);一旦輸入了無效字符,即使有效字符,toast也會繼續顯示。每次都會不斷移除無效字符。儘管EditText不顯示它,但SourceAsSpannableBuilder似乎仍保留無效字符。只有在輸入無效字符時才顯示敬酒的任何方法?感謝所有幫助... – c12
無視上面的問題,如果(結束==我+ 1){/ /顯示烤麪包}作品 – c12