Check if EditText is empty. [closed]

2018-12-31 17:26发布

I have 5 EditTexts in android for users to input. I would like to know if I could have a method for checking all the 5 EditTexts if they are null. Is there any way to do this??

30条回答
柔情千种
2楼-- · 2018-12-31 18:06

The following works for me all in one statement:

if(searchText.getText().toString().equals("")) 
    Log.d("MY_LOG", "Empty");

First I retrieve a text from the EditText and then convert it to a string and finally comparing it with "" using .equals method.

查看更多
何处买醉
3楼-- · 2018-12-31 18:08

Why not just disable the button if EditText is empty? IMHO This looks more professional:

        final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);  
        final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
        txtFrecuencia.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            toggle.setEnabled(txtFrecuencia.length() > 0);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }
       });
查看更多
公子世无双
4楼-- · 2018-12-31 18:09

I used TextUtils for this:

if (TextUtils.isEmpty(UsernameInfo.getText())) {
    validationError = true;
    validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
查看更多
柔情千种
5楼-- · 2018-12-31 18:10

Try this out: its in Kotlin

//button from xml
button.setOnClickListener{                                         
    val new=addText.text.toString()//addText is an EditText
    if(new=isNotEmpty())
    {
         //do something
    }
    else{
        new.setError("Enter some msg")
        //or
        Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
    }
}

Thank you

查看更多
长期被迫恋爱
6楼-- · 2018-12-31 18:11

Try this out with using If ELSE If conditions. You can validate your editText fields easily.

 if(TextUtils.isEmpty(username)) {
                userNameView.setError("User Name Is Essential");
                return;
         } else  if(TextUtils.isEmpty(phone)) {
                phoneView.setError("Please Enter Your Phone Number");
                return;
            }
查看更多
君临天下
7楼-- · 2018-12-31 18:11

use TextUtils.isEmpty("Text here"); for single line code

查看更多
登录 后发表回答