Android在Edittext中限制小数点后面的位数及小数点前面的位数,代码如下:
java实现:
private int behind = 2 //小数点后面限制位数
private int front = 3 //小数点前面限制位数
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > behind) {
s = s.toString().subSequence(0,
s.toString().indexOf(".") + (behind+1));
editText.setText(s);
editText.setSelection(s.length());
}
} else {
if (s.length() > front) {
editText.setText(s.subSequence(0, front));
editText.setSelection(s.length() - 1);
}
}
if (s.toString().trim().substring(0).equals(".")) {
s = "0" + s;
editText.setText(s);
editText.setSelection(behind);
}
if (s.toString().startsWith("0")
&& s.toString().trim().length() > 1) {
if (!s.toString().substring(1, behind).equals(".")) {
editText.setText(s.subSequence(0, 1));
editText.setSelection(1);
return;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
kotlin实现:
private val behind = 2
private val front = 3
edKM.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, start: Int, before: Int, count: Int) {
var s = p0.toString()
if (s.contains(".")) {
if (s.length - 1 - s.indexOf(".") > behind) {
s = s.subSequence(
0,
s.indexOf(".") + (behind + 1)
).toString()
edKM.setText(s)
edKM.setSelection(s.length);
}
} else {
if (s.length > front) {
edKM.setText(s.subSequence(0, front))
edKM.setSelection(s.length - 1)
}
}
if (s.trim().substring(0) == ".") {
s = "0$s"
edKM.setText(s);
edKM.setSelection(behind)
}
if (s.startsWith("0")
&& s.trim().length > 1
) {
if (s.substring(1, behind) != ".") {
edKM.setText(s.subSequence(0, 1));
edKM.setSelection(1);
return
}
}
}
})
END