问题描述
我是 android 移动开发的新手(Android Studio 原生开发 - 新知识).在这里我想问一个关于输入验证最佳实践的问题.据我们所知,当开发人员开发输入表单时.我们需要防止用户在文本字段中输入错误的内容.所以这是我的问题,
I am new to android mobile development (Android Studio native development - for new knowledge). And here I want to ask a question regarding best practice for input validation.As far we know, when a developer develop input form. We need to prevent a user from key in a wrong input into the text field. So here is my question,
- 我们可以创建一个仅用于验证目的的 java 文件吗?所有输入表单,必须只转到那个验证文件(如果一个应用程序中有多个输入页面屏幕).如果是,我怎样才能获得该技术的示例/链接/教程以用于我的学习研究.如果否,为什么?
- Can we create one java file for validation purpose only? All input form ,must go to that one validation file only (In case of many input page screen in one apps). If YES, how can I get an example/link/tutorial of that technique for my learning study. If NO, why?
从我个人的角度来看,它应该有实现该技术的方法.这样我们就不需要为每个 java 文件重新使用相同的代码(就干净的代码而言).不幸的是,我没有找到任何示例或教程.也许我搜索了错误的关键字或误读了.如果不存在这样的技术,那么输入验证的最佳实践是什么?
From my point of view personally, it should have a way to implement the technique. So that we didn't need to reuse same code all over again for each java file (in term of clean code). Unfortunately, I didn't find any example or tutorial for that. Maybe I search a wrong keyword or misread. And if there is no such technique exist, what are the best practice for input validation?
谢谢.
p/s:此线程用于在最佳实践中找到更好的方法.谢谢.
p/s: This thread for find a better way in best practice. Thank you.
推荐答案
这个 java 类实现了一个 TextWatcher
来观察"你的编辑文本,观察对文本所做的任何更改:
This java class implements a TextWatcher
to "watch" your edit text, watching any changes done to the text:
public abstract class TextValidator implements TextWatcher {
private final TextView textView;
public TextValidator(TextView textView) {
this.textView = textView;
}
public abstract void validate(TextView textView, String text);
@Override
final public void afterTextChanged(Editable s) {
String text = textView.getText().toString();
validate(textView, text);
}
@Override
final public void
beforeTextChanged(CharSequence s, int start, int count, int after) {
/* Needs to be implemented, but we are not using it. */
}
@Override
final public void
onTextChanged(CharSequence s, int start, int before, int count) {
/* Needs to be implemented, but we are not using it. */
}
}
并且在您的 EditText
中,您可以将该文本观察器设置为其侦听器
And in your EditText
, you can set that text watcher to its listener
editText.addTextChangedListener(new TextValidator(editText) {
@Override public void validate(TextView textView, String text) {
/* Insert your validation rules here */
}
});
这篇关于最佳实践:输入验证 (Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!