安卓:我如何可以验证的EditText输入? [英] Android: How can I validate EditText input?
问题描述
我需要做的形式输入验证一系列EditTexts的。我使用OnFocusChangeListeners来触发用户类型到每个一个接一个地验证,但是这并不表现为所需的最后的EditText
如果我点击完成按钮,同时输入到最后的EditText那么InputMethod断开,但在技术上重点是从来没有失去对的EditText(等验证永远不会发生)。
什么是最好的解决办法?
我应该监视时InputMethod每个EditText上解除绑定,而不是当焦点的变化?如果是这样,怎么样?
你为什么不使用 TextWatcher
?
既然你有大量的的EditText
箱进行验证,我觉得有以下应适合你:
- 您的活动器具
android.text.TextWatcher
接口 - 您添加框TextChanged听众对你的EditText箱
txt1.addTextChangedListener(本);
txt2.addTextChangedListener(本);
txt3.addTextChangedListener(本);
<醇开始=3>
afterTextChanged(编辑S)
方法如下: @覆盖
公共无效afterTextChanged(编辑S){
//验证code到这里
}
在编辑小号
并没有真正帮助查找的EditText框的文本正在改变。但是你可以直接检查的的EditText框的内容类似
字符串txt1String = txt1.getText()的toString()。
//验证txt1String
中相同的方法。我希望我是清楚的,如果我是,它可以帮助! :)
编辑:对于更简洁的方法请参考克里斯托弗·佩里的下面的答案。
I need to do form input validation on a series of EditTexts. I'm using OnFocusChangeListeners to trigger the validation after the user types into each one, but this doesn't behave as desired for the last EditText.
If I click on the "Done" button while typing into the final EditText then the InputMethod is disconnected, but technically focus is never lost on the EditText (and so validation never occurs).
What's the best solution?
Should I be monitoring when the InputMethod unbinds from each EditText rather than when focus changes? If so, how?
Why don't you use TextWatcher
?
Since you have a number of EditText
boxes to be validated, I think the following shall suit you :
- Your activity implements
android.text.TextWatcher
interface - You add TextChanged listeners to you EditText boxes
txt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);
- Of the overridden methods, you could use the
afterTextChanged(Editable s)
method as follows
@Override
public void afterTextChanged(Editable s) {
// validation code goes here
}
The Editable s
doesn't really help to find which EditText box's text is being changed. But you could directly check the contents of the EditText boxes like
String txt1String = txt1.getText().toString();
// Validate txt1String
in the same method. I hope I'm clear and if I am, it helps! :)
EDIT: For a cleaner approach refer to Christopher Perry's answer below.
这篇关于安卓:我如何可以验证的EditText输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!