Android: Check if EditText is Empty when inputType is set on Number/Phone

后端 未结 9 1352
孤独总比滥情好
孤独总比滥情好 2020-12-25 15:37

I have an EditText in android for users to input their AGE. It is set an inputType=phone. I would like to know if there is a way to check if this EditText is null

相关标签:
9条回答
  • 2020-12-25 15:52

    I found that these tests fail if a user enters a space so I test for a missing hint for empty value

    EditText username = (EditText) findViewById(R.id.editTextUserName);
    
    EditText password = (EditText) findViewById(R.id.editTextPassword);
    
    // these hint strings reflect the hints attached to the resources
    
    if (username.getHint().equals("Enter your username") || password.getHint().equals("Enter Your Password")){
          // enter your code here 
    
    } else {
          // alls well
    }
    
    0 讨论(0)
  • 2020-12-25 15:59
    EditText textAge;
    textAge = (EditText)findViewByID(R.id.age);
    if (TextUtils.isEmpty(textAge))
    {
    Toast.makeText(this, "Age Edit text is Empty", Toast.LENGTH_SHORT).show();
    //or type here the code you want
    }
    
    0 讨论(0)
  • 2020-12-25 16:02

    Add Kotlin getter functions

    val EditText.empty get() = text.isEmpty() // it == ""
    // and/or
    val EditText.blank get() = text.isBlank() // it.trim() == ""
    

    With these, you can just use if (edittext.empty) ... or if (edittext.blank) ...

    If you don't want to extend this functionality, the original Kotlin is:

    edittext.text.isBlank()
    // or
    edittext.text.isEmpty()
    
    0 讨论(0)
  • 2020-12-25 16:06

    editText.length() usually works for me try this one

    if((EditText) findViewByID(R.id.age)).length()==0){
       //do whatever when the field is null`
    }
    
    0 讨论(0)
  • 2020-12-25 16:08

    Simply do the following

    String s = (EditText) findViewByID(R.id.age)).getText().toString();
    TextUtils.isEmpty(s);
    
    0 讨论(0)
  • 2020-12-25 16:10

    First Method

    Use TextUtil library

    if(TextUtils.isEmpty(editText.getText().toString()) 
    {
        Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
        return;
    }
    

    Second Method

    private boolean isEmpty(EditText etText) 
    {
            return etText.getText().toString().trim().length() == 0;
    }
    
    0 讨论(0)
提交回复
热议问题