最近项目需要输入价格,但是不想让用户在小数点后面输入太多,所以我封装了一个。当用户输入小数点的时候 监听小数点后面的位数,只要大于两位就立马删掉,封装好了,直接可以拿过来用!
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
43
44
45
|
public
static
void
setPricePoint(
final
EditText editText) {
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(
"."
) >
2
) {
s = s.toString().subSequence(
0
,
s.toString().indexOf(
"."
) +
3
);
editText.setText(s);
editText.setSelection(s.length());
}
}
if
(s.toString().trim().substring(
0
).equals(
"."
)) {
s =
"0"
+ s;
editText.setText(s);
editText.setSelection(
2
);
}
if
(s.toString().startsWith(
"0"
)
&& s.toString().trim().length() >
1
) {
if
(!s.toString().substring(
1
,
2
).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
}
});
}
|