Android: Check if EditText is Empty when inputType

2020-02-21 08:33发布

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.

I've already looked at this question: Check if EditText is empty. but it does not address the case where inputType=phone.

These, I've checked already and do not work:

(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.

Thank you for your help.

9条回答
戒情不戒烟
2楼-- · 2020-02-21 09:02

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

if((EditText) findViewByID(R.id.age)).length()==0){
   //do whatever when the field is null`
}
查看更多
时光不老,我们不散
3楼-- · 2020-02-21 09:04

Simply do the following

String s = (EditText) findViewByID(R.id.age)).getText().toString();
TextUtils.isEmpty(s);
查看更多
可以哭但决不认输i
4楼-- · 2020-02-21 09:07

Try this. This is the only solution i got

String phone;

try{ phone=(EditText) findViewByID(R.id.age)).getText().toString();

} catch(NumberFormatException e){

Toast.makeText(MainActivity.this, "plz enterphone Number ", Toast.LENGTH_SHORT).show(); return;

}

查看更多
登录 后发表回答