我在使用来自 EditText 的验证输入时遇到问题。每当我单击 SaveData 按钮时,无论它是否有效,都会弹出对话框。这是我写的示例:
验证类:
package android.week04Lab03;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.webkit.URLUtil;
import android.widget.EditText;
public class Validation {
public boolean isEmpty(EditText txt){
if(txt.getText().toString().equals("")){
return false;
} else
return true;
}
public boolean isURL (EditText txt){
if (!URLUtil.isValidUrl(txt.getText().toString())){
return false;
}
return true;
}
public boolean isEmail (EditText txt){
String isEmail = "^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$";
Pattern isEmailPattern = Pattern.compile(isEmail);
Matcher mailMatcher = isEmailPattern.matcher(txt.getText().toString());
if (!mailMatcher.find()) {
return false;
}
return true;
}
}
这是活动课
public class MetaData extends Activity {
Validation validator;
ImageView angel;
EditText name, loc, keyword, date, mail;
ToggleButton share;
RatingBar rating;
Button save;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meta_data);
name = (EditText) findViewById(R.id.name);
..........................
public void saveData(View v) {
Validation validator = new Validation();
if (!validator.isEmpty(name)) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Input Validation Warning");
alert.setIcon(R.drawable.ic_launcher);
alert.setMessage("Error found, please enter your information correctly!");
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alert.show();
}
}