问题
I'm trying to add input validation to a set of three EditTexts that the user enter numeric values into. The problem I'm facing is for the calculation to work the user can't enter zero as one of the input fields or the application will crash.
I tried to implement the following to prevent zero from being entered and show a warning message.I get an error stating that "unable to start activity calcResult" which is the activity that shows the calculation.
This is the link to the error log: http://pastebin.com/hDsabjR6
I understand from this that the zero value is still slipping through the validation but I don't know why?
String getoffsetlength = offsetLength.getText().toString();
if (getoffsetlength.trim().equals('0')) {
Toast.makeText(this, "Enter number greater than 0!", Toast.LENGTH_SHORT).show();
return;
}
The application crashes when I have used this validation in the app.Any ideas as to where I have messed up with this implementation?
回答1:
Just add android:digits="123456789" to the EditText in XML. This way the user won't be able to input 0
[EDIT]
However, if you want to avoid the user from entering 0 only at the beginning, then use this:
code_text.addTextChangedListener(new TextWatcher(){
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (code_text.getText().toString().matches("^0") )
{
// Not allowed
Toast.makeText(context, "not allowed", Toast.LENGTH_LONG).show();
code_text.setText("");
}
}
@Override
public void afterTextChanged(Editable arg0) { }
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
});
回答2:
Try this instead
if(getoffsetlength.trim().equalsIgnoreCase("0"){
Toast.makeText(this, "Enter number greater than 0!", Toast.LENGTH_SHORT).show();
return;
}
回答3:
you can also use below code
int PreviousLen;
boolean keyDel;
etActLoginMobNo.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mPreviousLen = s.length();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
keyDel = mPreviousLen > s.length();
if(!keyDel){
if (etActLoginMobNo.getText().toString().startsWith("0")) {
etActLoginMobNo.setText("");
Toast.makeText(context, R.string.enter_mobile_no_without_zero, Toast.LENGTH_SHORT).show();
}
}
}
来源:https://stackoverflow.com/questions/20248674/how-to-prevent-user-from-entering-zero-as-an-input