我想用某个值(不是最大长度)限制 EditText 条目。
示例 - 最大值为 $100。
可能的最大值输入为票价:100、100.0、100.00
所以我不能用最大长度来限制它。
是否可以限制用户输入值的时间?
或者检查 TextChangeListener 上if(edittextvalue>100)
的值是唯一的选择?
是否可以限制用户输入值的时间?
是的,您应该使用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
void onTextChanged (CharSequence s, 整数开始, int 之前, int count)调用此方法是为了通知您,在 s 中,从 start 开始的计数字符刚刚替换 以前有长度的旧文本。尝试犯错 从此回调更改为 s。
将
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) {
}
});
希望这会有所帮助。