我需要一个可以添加数千个分隔符的textwatcher,所以我发现了这个:
package utils;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;
/**
* Created by Robby on 4/07/2014.
*/
public class NumberTextWatcher implements TextWatcher {
@SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
private final TextView currencyIndicator;
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private EditText et;
public NumberTextWatcher(TextView currencyIndicator, EditText et) {
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.GERMANY);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
df = new DecimalFormat("#,###.##", otherSymbols);
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###", otherSymbols);
this.et = et;
hasFractionalPart = false;
this.currencyIndicator = currencyIndicator;
}
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
if (s != null && s.length() > 0) {
currencyIndicator.setVisibility(View.VISIBLE);
} else {
currencyIndicator.setVisibility(View.GONE);
}
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
因此,当我输入100000时,它将edittext设置为100.000等...
当我注释掉afterTextChanged块时,它非常流畅,所以它必须是那里导致swiftkey应用程序滞后的东西。
有更有效的方法吗?或者这只是一个我不应该注意的swiftkey中的错误?
在股票键盘上,我没有任何延迟。