27

I have an EditText and a Button in my application.

When the button is clicked,the text entered in the EditText is added to a ListView.

I want to disable the Button if the EditText is empty.How to do this ?

This is my code for button click

ImageButton imb=(ImageButton)findViewById(R.id.btn_send);
            imb.setOnClickListener(new OnClickListener()
            {
             @Override
             public void onClick(View arg0) 
             { 
                 EditText et = (EditText)findViewById(R.id.EditText1);

                  String str = et.getText().toString();
                  web1.add(str);
                  Toast.makeText(ShoutSingleProgram.this, "You entered...."+str, Toast.LENGTH_SHORT).show();
                  adapter1.notifyDataSetChanged();
                  et.setText("");

                    }
            });
            }

How can i do this ?

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
Nevaeh
  • 1,519
  • 7
  • 24
  • 45

15 Answers15

54
    editText1.addTextChangedListener(new TextWatcher() {

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

           if(s.toString().trim().length()==0){
                button.setEnabled(false);
              } else {
                button.setEnabled(true);
              }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
Deep Patel
  • 2,584
  • 2
  • 15
  • 28
drulabs
  • 3,071
  • 28
  • 35
9

Use TextChangedListener and initially disable ImageButton in onCreate().

Try this

public class MyActivity extends Activity {

ImageButton imb;
EditText et;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imb = (ImageButton) findViewById(R.id.btn_send);
    et = (EditText) findViewById(R.id.EditText1);

    imb.setEnabled(false); // set button disable initially

    et.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

            if (s.toString().equals("")) {
                imb.setEnabled(false);
            } else {
                imb.setEnabled(true);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

}

}
Chirag Ghori
  • 4,231
  • 2
  • 20
  • 35
6

Simple just check the condition in onCreate

if (et.getText().toString().trim().equals("")){
  button.setEnabled(false);
}
else{
button.setEnabled(true);
}
InnocentKiller
  • 5,234
  • 7
  • 36
  • 84
6

Here's a super simple answer in Kotlin.

Just replace 'EditText' and 'Button' with your own.

Button.isEnabled = false
        EditText.addTextChangedListener(object: TextWatcher {
            override fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
                Button.isEnabled = s.toString().trim{ it <= ' ' }.isNotEmpty()
            }
            override fun beforeTextChanged(s:CharSequence, start:Int, count:Int,
                                           after:Int) {
            }
            override fun afterTextChanged(s: Editable) {
            }
        })

For Multiple EditTexts go

Button.isEnabled = false
            val editTexts = listOf(editText1, editText2, editText3, editText4, editText5, editText6)
for (editText in editTexts) {
            editText.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                var et1 = editText1.text.toString().trim()
                var et2 = editText2.text.toString().trim()
                var et3 = editText3.text.toString().trim()
                var et4 = editText4.text.toString().trim()
                var et5 = editText5.text.toString().trim()
                var et6 = editText6.text.toString().trim()

                computeBtn.isEnabled = et1.isNotEmpty()
                        && et2.isNotEmpty()
                        && et3.isNotEmpty()
                        && et4.isNotEmpty()
                        && et5.isNotEmpty()
                        && et6.isNotEmpty()
            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int, after: Int) {
            }

            override fun afterTextChanged(
                s: Editable) {
            }
        })
        }
Stevo
  • 248
  • 4
  • 8
5

Easy Solution

This is very easy to implement in Data-Binding. I hope you are aware of it at this time. You can manage Button with EditText via only XML.

android:enabled="@{etName.text.length() > 0 &amp;&amp; etPassword.text.length() > 5}"

Which is equivalent to

button.setEnabled(etName.getText().length() > 0 && etPassword.getText().length() > 5 );
  • Here &amp; is HTML entity which denotes to &. There can be any operator like &.

  • etName & etPassword are EditTexts ids.

Complete XML -

<LinearLayout
    >

    <EditText
        android:id="@+id/etName"
        />

    <EditText
        android:id="@+id/etPassword"
        />

    <Button
        android:enabled="@{etName.text.length() > 5 &amp;&amp; etPassword.text.length() > 5}"
        />

</LinearLayout>
Community
  • 1
  • 1
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • Does the button gets enabled again just after those conditions are met? if not, I think your answer is eighter useless or irrelevant. – Emad Razavi Feb 02 '21 at 14:02
3

I used TextUtils for a concise solution:

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            button.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
        }

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

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
mharper
  • 3,212
  • 1
  • 23
  • 23
1

Add a TextWatcher to your EditText, so that when you change the text inside it, you Button enables or disables itself.

agamov
  • 4,407
  • 1
  • 27
  • 31
1

Initally in onCreate() disable the button. Then add a addTextChangedListenerto the edit text. within that check the edittext length and disable if it is 0 or otherwise enable it

1

If you want to use an object oriented solution and reuse your code

public abstract class EmptyTextWatcher implements TextWatcher
{
    public abstract void onEmptyField();

    public abstract void onFilledField();

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        if (s.toString().trim().length() == 0)
        {
            onEmptyField();
        } else
        {
            onFilledField();
        }
    }

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

    }



    @Override
    public void afterTextChanged(Editable s)
    {

    }

}

so you can use it just doing

textView.addTextChangedListener(new EmptyTextWatcher()
        {

            @Override
            public void onEmptyField()
            {
                button.setEnabled(false);
            }

            @Override
            public void onFilledField()
            {
                button.setEnabled(true);
            }
        });
Angelo Nodari
  • 365
  • 7
  • 14
0

on Oncreate() , before button click you should check the condition as,

   ImageButton imb=(ImageButton)findViewById(R.id.btn_send);
   EditText et = (EditText)findViewById(R.id.EditText1);
   if(et.getText().toString().equals("")
   {
   imb.setEnabled(false);
   }

   imb.setOnClickListener(new OnClickListener()
        {
         @Override
         public void onClick(View arg0) 
         { 
             EditText et = (EditText)findViewById(R.id.EditText1);

              String str = et.getText().toString();
              web1.add(str);
              Toast.makeText(ShoutSingleProgram.this, "You entered...."+str, Toast.LENGTH_SHORT).show();
              adapter1.notifyDataSetChanged();
              et.setText("");

                }
        });
0

When you want to disable the editText there You will use below code

editText.setEnabled(false); 
editText.setFocusable(false);
PothiraJ
  • 65
  • 14
0

you check the status of an edittext at runtime using the text watcher. the below code counts the text length and disables if the length is zero. use this code:

EditText mEditText = new EditText(this);
    mEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            if (s.length() == 0) {
                button.setEnabled(false);
            }
                            else {
                            button.setEnabled(true);
                        }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
Ashwin S Ashok
  • 3,623
  • 2
  • 29
  • 36
0

if anyone was wondering here is the kotlin version of the code

editText1.addTextChangedListener(object: TextWatcher {
        override fun onTextChanged(s:CharSequence, start:Int, before:Int, count:Int) {
            if (s.toString().trim({ it <= ' ' }).isEmpty())
            {
                button.setEnabled(false)
            }
            else
            {
                button.setEnabled(true)
            }
        }
        override fun beforeTextChanged(s:CharSequence, start:Int, count:Int,
                              after:Int) {
            // TODO Auto-generated method stub
        }
        override fun afterTextChanged(s: Editable) {
            // TODO Auto-generated method stub
        }
    })
BigZee
  • 456
  • 5
  • 22
  • if i'm right `s.toString().trim({ it <= ' ' }).isEmpty()` is the same as `s.isBlank()`. in that case onTextChanged can be simplified to: `button.isEnabled = s.isBlank()` – tieskedh May 22 '18 at 11:46
0

Same as the top accepted answer, but simplified. Remember to wrap the condition in () so it uses the boolean.

editText1.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
         button.setEnabled((s.toString().trim().length()>0));     
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
});
Z3r0CooL
  • 131
  • 1
  • 7
0

Here is my code:

EditText TextBox1, TextBox2;
Button btn;

 //Code of onCreate() method is start here:
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextBox1 = findViewById(R.id.TextBox1);
    TextBox2 = findViewById(R.id.TextBox2);

    TextBox1.addTextChangedListener(CheckEmptyTxtBoxes);
    TextBox2.addTextChangedListener(CheckEmptyTxtBoxes);
    btn = findViewById(R.id.button);
  }

    //Code of TechWatcher listener start here:
    private TextWatcher CheckEmptyTxtBoxes = new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
        try {
            String txtbox1 = TextBox1.getText().toString().trim();
            String txtbox2 = TextBox2.getText().toString().trim();
            if (!txtbox1.isEmpty() && !txtbox2.isEmpty()) {
                btn.setEnabled(true);
                btn.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#0307F4")));
            } else {
                btn.setEnabled(false);
                btn.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#8486FB")));
            }

        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "OnTextChanged method error", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};
cigien
  • 57,834
  • 11
  • 73
  • 112
Mayank
  • 14
  • 2
  • Please note that linking to your own content when it's not relevant to the question can be considered spam on this site. You're welcome to advertise your content in your profile page, but please refrain from doing so in questions and answers on the site. – cigien Oct 29 '22 at 07:04