How to validate edit text input in Android?

◇◆丶佛笑我妖孽 提交于 2019-12-25 04:12:35

问题


I've added input validation to a set of edit texts in a dialog message using the setError method in Android.

But when I test it by leaving some of the edit texts blank and clicking "ok" on the dialog, the dialog closes without triggering a prompt to enter values.

Can anyone see what is wrong with this implementation?

I think it may be something to do with a call to close the dialog before input validation is triggered.

This is how I've set the input validation based on the 4th answer in this question, Check if EditText is empty.:

    else if(TextUtils.isEmpty(strColour)) {
        colourText.setError("Please enter a value");
        return;
     }
}
   dialog.cancel(); 
}

回答1:


That's because you are calling dialog.cancel() irrespective of error(s). Call this method only if there is no error. Keep a track of error using a boolean. If error exist make it false otherwise keep it true and call the dialog.cancel() method only if the boolean is true.



来源:https://stackoverflow.com/questions/27788043/how-to-validate-edit-text-input-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!