Android - 在centain VALUE(例如$ 100)后限制EditText条目
问题描述:
我想用特定值(不是最大长度)限制EditText条目。
示例 - MaxValue是$ 100。
可能的最高值输入 100,100.0,100.00
所以我不能与最大长度限制它。
是否可以限制用户输入值的时间?
或检查值if(edittextvalue>100)
对TextChangeListener是唯一的选择吗?
答
是否可以限制用户输入值?
是的,您应该使用TextWatcher
。我希望这是最好的方式。
当一个类型的对象附加到可编辑时,当文本被更改时,将调用其方法 。
private final TextWatcher TxtWatecherExample= new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Add your LOGIC
if()
{}
else
{}
}
}
public void afterTextChanged(Editable s) {
};
无效onTextChanged(CharSequence中, INT开始, INT之前, 诠释计数)这个方法被调用来通知您,S中,计从开始处开始的字符刚刚替换了以前长度为 的旧文本。尝试从此回调中对 进行更改是错误的。
+0
Downvoting。这个答案没有给任何解决方案。 op已经从'TextChangeListener'知道了它。 –
答
的
addTextChangedListener
事件添加到您的editText
这样。
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
try {
double value = Double.parseDouble(editText.getText().toString());
if (value >= 100.0) {
// Your code goes here.
} else {
// Your code goes here.
}
} catch (Exception ex) {
// Handle empty string. Since we're passing the edittext value.
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
希望这会有所帮助。
在TextWatcher中检查是唯一的方法。 –