Android:如何验证 EditText 输入? [英] Android: How can I validate EditText input?

查看:32
本文介绍了Android:如何验证 EditText 输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对一系列 EditText 进行表单输入验证.我正在使用 OnFocusChangeListeners 在用户输入每个内容后触发验证,但对于最后一个 EditText 来说,这并不符合预期.

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.

如果我在输入最终 EditText 时单击完成"按钮,则 InputMethod 断开连接,但技术上的焦点永远不会丢失在 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?

我是否应该监控 InputMethod 何时从每个 EditText 解除绑定而不是在焦点发生变化时进行监控?如果是,怎么办?

Should I be monitoring when the InputMethod unbinds from each EditText rather than when focus changes? If so, how?

推荐答案

你为什么不使用 TextWatcher ?

由于您有许多要验证的 EditText 框,我认为以下内容适合您:

Since you have a number of EditText boxes to be validated, I think the following shall suit you :

  1. 您的 Activity 实现了 android.text.TextWatcher 接口
  2. 向 EditText 框添加 TextChanged 侦听器

txt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);

  1. 在重写的方法中,您可以使用 afterTextChanged(Editable s) 方法,如下所示
  1. Of the overridden methods, you could use the afterTextChanged(Editable s) method as follows

@Override
public void afterTextChanged(Editable s) {
    // validation code goes here
}

Editable s 并不能真正帮助找到哪个 EditText 框的文本正在被更改.但是您可以直接检查 EditText 框的内容,例如

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! :)

有关更简洁的方法,请参阅下面的Christopher Perry 的回答.

For a cleaner approach refer to Christopher Perry's answer below.

这篇关于Android:如何验证 EditText 输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆