【发布时间】:2014-05-26 08:29:29
【问题描述】:
我正在尝试对需要过滤非数字字符和点的编辑文本实施过滤器。我可以使用编辑文本或输入类型的数字标签,但似乎设备之间存在细微差别,例如有些设备即使在 EditText 中过滤它们也会显示点字符。
这是 afterTextChanged 方法
if(isEditing) return;
Log.v("Information", "last: " + s.charAt(s.length()-1));
Log.v("Information", "Full string before: " + s.toString());
if(s.charAt(s.length()-1) == '.') {
Log.v("Information", "DOT!");
isEditing = true;
String currentText = s.toString().replace(".", "");
s.replace(0, s.length(), currentText);
isEditing = false;
Log.v("Information", "Full string after: " + s.toString());
return;
}
else if(!Character.isDigit(s.charAt(s.length()-1))) {
Log.v("Information", "NOT DIGIT!");
isEditing = true;
String currentText = "";
if(s.length() > 1)
currentText = s.toString().substring(0, s.length()-1);
s.replace(0, s.length(), currentText);
isEditing = false;
Log.v("Information", "Full string after: " + s.toString());
return;
}
这是输出
last: 6
Full string before: 6
Full string after: 6
last: 6
Full string before: 66
Full string after: 66
last: h
Full string before: 66h
NOT DIGIT!
Full string after: 66
last: h
Full string before: 66hh
NOT DIGIT!
Full string after: 66h
如您所见,在我删除第一个“h”后,当我输入另一个 h 时,字符串变为“66hh”,它应该是“66h”,因为我已经删除了第一个 h。什么可能导致阻止我对可编辑 s 进行更改?
编辑: 忘了说,这是我的EditText
<core.globals.views.EditTextWithCursorWatcher
android:id="@+id/edittext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="8"
android:background="@null"
android:ellipsize="end"
android:gravity="right"
android:hint="0,00"
android:maxLength="15"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:singleLine="true"
android:text="0,00"
android:textColor="#ff414141"
android:textColorHint="#ff414141"
android:textSize="16sp" />
【问题讨论】:
-
尝试使用
currentText = s.toString().replace(s.substring(s.length() - 1), ""); -
我认为问题不在于 currentText。插入“h”后的“完整字符串:66”意味着我的删除已确认,这意味着 currentText 正在工作。问题是在插入第二个'h'之后,“Full string before: 66hh”应该是“Full string before: 66”。
-
您只想输入数字?
-
数字加逗号。但是更改输入类型或声明 digit:0123... 或使用输入过滤器进行过滤不适用于某些设备。无论我如何过滤,有些设备总是显示点。
-
我不知道为什么,但是从 EditText 对象更改可编辑而不是方法参数中的可编辑解决了它...
标签: android android-edittext textwatcher