Android EditText validation

非 Y 不嫁゛ 提交于 2019-12-13 04:32:31

问题


I have two EditText like editText1 and editText2.

I am taking input from EditText to name1 and name2.

Now I want to validate that the EditText are not empty before clicking on ok button.
For this I used:

if(editText1==NULL && editText2==NULL) {
    textView.setText("please enter Names");
} else {
    other code;
}

But its not validating, and with empty EditText it is showing result on clicking ok button.
I have also tried in this way:

if(name1==NULL && name2==NULL) {
    textView.setText("please enter Names");
} else {
    other code;
}

What to do?


回答1:


Please use:

 if(name1.compareTo("") == 0 || name2.compareTo("") == 0) {
     // Your piece of code for example
     Toast toast=Toast.makeText(getApplicationContext(), "ENTER NAMES", Toast.LENGTH_SHORT);  
     toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
     toast.show();
 } else {
     // Your code  
 }

This will work definitely for sure.




回答2:


Try this:

if(editText1.getText().toString().trim().equals("") 
    && editText2.getText().toString().trim().equals(""))
{
    textView.setText("Please enter Names");
}
else
{
    // other code
}



回答3:


Try like this name1.equals("") in place of name1==NULL

if(name1.equals("") && name2.equals(""))
{
  textView.setText("please enter Names");
 }
  else
 {
    other code;
 }



回答4:


if(name1.compareTo("") == 0 || name2.compareTo("") == 0)
{
    // Your piece of code for example
}  



回答5:


you can use:

if(name.compareTo("") == 0 || name.compareTo(null) == 0) {}



回答6:


This works very well for me, try this

if(editText1.getText().toString().length == 0 && editText2.getText().toString().length == 0)

{
    textView.setText("Please enter names");
}
else
{
    //some other actions to perform
}



回答7:


if(editText1.getText().toString().length() > 0 && editText2.getText().toString().length() > 0)
{
    textView.setText("Please enter Names");
}
else
{
    // Other code
}


来源:https://stackoverflow.com/questions/18050412/android-edittext-validation

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