我试图在编辑文本上实现过滤器,我需要过滤非数字字符和点。我可以使用编辑文本或输入类型的数字标签,但似乎设备之间存在细微差别,就像有设备显示点字符,即使您在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" />
答案 0 :(得分:0)
我只是使用自定义Inputfilter创建工作演示。试试这个
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edtText = (EditText) findViewById(R.id.edtText);
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
if (!Character.isDigit(source.charAt(0))) {
if (source.equals(",")) {
if (dend == 0) {
return "";
} else {
if (("" + edtText.getText().toString().charAt(edtText.getText().toString().length() - 1)).equals(",")) {
return "";
} else {
return null;
}
}
} else {
return "";
}
}
} catch (Exception e) {
}
return null;
}
};
edtText.setFilters(new InputFilter[] { filter });
}