Welcome to Ray's Blog

Stay Hungry Stay Foolish - Steve Jobs

0%

android EditText限制输入框小数位数


概述

[转]Android EditText 限制输入框小数位数
[参考链接](android EditText 限制输入框小数位数)

方法

  1. 先看看 XML 布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
/>
```
**注意设置可输入小数:`android:inputType="numberDecimal"`**;

<!--more-->

2. 过滤文本方法
~~~java
// 输入框小数的位数
private static final int DECIMAL_DIGITS = 2;
private InputFilter lengthFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
//输入小数,自动补0
if (dest.length() == 0 && source.equals(".")) {
return "0.";
}
String dValue = dest.toString();
String[] splitArray = dValue.split("\\.");
if (splitArray.length > 1) {
String dotValue = splitArray[1];
if (dotValue.length() == DECIMAL_DIGITS) {
return "";
}
}
return null;
}
}
~~~

3. 给EditText设置gu过滤器
~~~java
mEt.setFilters(new InputFilter[] { lengthfilter });
~~~

4. Enjoy!