EditText 限制一个小数点
时间: 2024-03-05 17:51:35 浏览: 26
可以使用 InputFilter 进行限制,具体步骤如下:
1. 创建一个 InputFilter 对象:
```
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// 判断是否已经存在小数点
if (dest.toString().contains(".") && source.toString().equals(".")) {
return "";
}
return null;
}
};
```
2. 将 InputFilter 对象设置给 EditText:
```
EditText editText = findViewById(R.id.editText);
editText.setFilters(new InputFilter[] {filter});
```
这样,当用户输入第二个小数点时,就会被过滤掉,从而实现了限制。
相关问题
Android,使用EditText限制1位小数点
可以使用 InputFilter 来限制 EditText 输入的小数位数。具体步骤如下:
1. 创建一个 InputFilter 对象:
```
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// 判断是否已经存在小数点
if (dest.toString().contains(".")) {
// 已经存在小数点,只允许输入小数点后一位
int index = dest.toString().indexOf(".");
int length = dest.toString().substring(index).length();
if (length > 1) {
return "";
}
} else {
// 不存在小数点,允许输入小数点和数字
if (!source.toString().matches("[0-9.]")) {
return "";
}
}
return null;
}
};
```
2. 将 InputFilter 对象设置给 EditText:
```
EditText editText = findViewById(R.id.editText);
editText.setFilters(new InputFilter[] {filter});
```
这样,当用户输入小数点时,只允许输入小数点后一位,从而实现了限制。
Android,使用EditText限制2位小数点
可以使用 InputFilter 来限制 EditText 输入的小数位数。具体步骤如下:
1. 创建一个 InputFilter 对象:
```
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// 判断是否已经存在小数点
if (dest.toString().contains(".")) {
// 已经存在小数点,只允许输入小数点后两位
int index = dest.toString().indexOf(".");
int length = dest.toString().substring(index).length();
if (length > 2) {
return "";
}
} else {
// 不存在小数点,允许输入小数点和数字
if (!source.toString().matches("[0-9.]")) {
return "";
}
}
return null;
}
};
```
2. 将 InputFilter 对象设置给 EditText:
```
EditText editText = findViewById(R.id.editText);
editText.setFilters(new InputFilter[] {filter});
```
这样,当用户输入小数点时,只允许输入小数点后两位,从而实现了限制。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)