EditText要加属性 android:inputType=“numberDecimal”
android:inputType="numberDecimal"
txt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int digits= 2;
String content = s.toString();
if (content.startsWith(".")) {
content = "0.";
}
if (content.startsWith("0")) {
if (content.length() > 1 && !content.substring(1, 2).equals(".")) {
content = content.substring(1);
}
}
if (content.contains(".")) {
int pointIndex = content.indexOf(".");
if (content.length() - 1 - pointIndex > digits) {
content = content.substring(0, pointIndex + digits+1);
}
}
txt.removeTextChangedListener(this);
txt.setText(content);
txt.setSelection(content.length());
txt.addTextChangedListener(this);
if (content.endsWith(".")) {
content = content.substring(0, content.indexOf("."));
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
|