の小数点入力の後に 2 つの数値のみを追加しようとしていEditText
ます。
TextWatcher
というわけで、入力中をチェックするa を実装しましたstring
。
以下で使用している関数は驚くほど機能しますが、大きな欠陥が 1 つあります。任意の値を入力すると、小数点が追加され、その小数点が削除され、さらに値が追加されます。入力として受け入れられる値は 3 つだけです。
事例:を入力300.
したのに を入力したかった3001234567
ので、小数点を削除し.
て に足す1234567
と300
、 のみ123
が受け入れられ、残りは無視されます。
これをどのように処理すればよいですか?任意の提案をいただければ幸いです。
私のコード:
price.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
if (arg0.length() > 0) {
String str = price.getText().toString();
price.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
count--;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(100);
price.setFilters(fArray);
//change the edittext's maximum length to 100.
//If we didn't change this the edittext's maximum length will
//be number of digits we previously entered.
}
return false;
}
});
char t = str.charAt(arg0.length() - 1);
if (t == '.') {
count = 0;
}
if (count >= 0) {
if (count == 2) {
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(arg0.length());
price.setFilters(fArray);
//prevent the edittext from accessing digits
//by setting maximum length as total number of digits we typed till now.
}
count++;
}
}
}
});